我想如何處理我的例外,並仍然避免重複的代碼的意見。以下是我想如何處理這種情況。處理多個例外,但避免重複的代碼
避免重複代碼的情況(我不喜歡在這裏使用instanceof)。
try{
//some code which might throw multiple different exceptions.
} catch(Exception e) {
//do something here
if(e instanceof IOException) {
// do something only when this type exception occurred.
} else if(e instanceof SQLException){
// do something only when this type of exception occurred.
} else if(e instanceof SomeCustomExceptionMaybe){
// do something only when this type of exception occurred.
}
//continue exception handling here.
}
與
沒有的instanceof情況(我真的不喜歡重複的代碼)。
try{
//some code which might throw multiple different exceptions.
} catch(IOException e1) {
// The order must always be this.
// do something general for each exception
// do something only with this exception
// do something general again.
} catch(SomeCustomExceptionMaybe e2) {
// The order must always be this.
// do something general for each exception
// do something only with this exception
// do something general again.
} //and so on
PS:儘量避免在Java 7的異常處理給出答覆時:
catch(IOException | SomeOtherTypeException | AnotherTypeException)
編輯:我不使用Java 7的,這就是爲什麼我問基於java 7,避免響應。
把應例外塊內執行的代碼放到一個方法,從內部調用方法你異常塊? –
你能詳細說明爲什麼你確實不想使用Java 7異常處理? –
@CeilingGecko:我想,它仍然需要一個instanceof檢查。 –