Alexey Zakharov
Alexey Zakharov

Reputation: 25102

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
   }
}
...

Upvotes: 9

Views: 4423

Answers (3)

Radon8472
Radon8472

Reputation: 4931

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
    }
}

Upvotes: 2

Shivan Dragon
Shivan Dragon

Reputation: 15219

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
}

Upvotes: 1

aioobe
aioobe

Reputation: 420951

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
   }
}
...

Upvotes: 9

Related Questions