Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
   }
}
...
like image 676
Alexey Zakharov Avatar asked Feb 03 '23 11:02

Alexey Zakharov


2 Answers

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
   }
}
...
like image 175
aioobe Avatar answered Feb 07 '23 10:02

aioobe


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
    }
}
like image 25
Radon8472 Avatar answered Feb 07 '23 11:02

Radon8472