当前位置: 动力学知识库 > 问答 > 编程问答 >

java - What is the proper way to handle exception inside callback?

问题描述:

I've got a callback with exception instance. Currently i handle it this way, but i think that there is a better way. Would like to hear some comment from Java expert. =)

...

onError(Exception e) {

if (e instanceof IOException) {

ioe = (IOException)e;

// do smth with ioe

} else if (e instanceof MyException) {

mye = (MyException)e;

// do smth with mye

}

}

...

网友答案:

I'm not 100% sure about what you mean by "handle exceptions inside callback", but the onError method you provided could be better expressed like this:

...
onError(Exception e) {
   try {
       throw e;
   } catch (IOException ioe) {
      // do smth with ioe
   } catch (MyException mye) {
      // do smth with mye
   }
}
...
网友答案:

I think you could override "onError" with subclasses of exceptions:

interface MyExceptionHandler  
{
    onError(Exception e) {
          // Default exception
    }
    onError(IOException ioe) {
          // do smth with ioe
    }
    onError(MyException mye) {
          // do smth with mye
    }
}
网友答案:

Well, you can use a try with multiple catch blocks, each catch block dealing with a narrower exception than the one after him, this way you no longer need the boiler plate code with the ifs:

try {
   doSomething();    
} catch(IOException ioe) {
   log.error("File not found"+ioe.getmessage();
} catch(Exception e) {
   //... etc
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: