Best practice for handling multiple exceptions in similar ways in Java - java

Is there a canonical best-way-to-do-this for the following situation?
I have a block of code that can generate a number of different exceptions, each of which is handled by hiding a dialog, displaying an error message and running an onDisconnect() method. The catch is that, for each exception, the error message needs to be different. As I see it, there are two choices. The first is to catch Exception, then handle the various exceptions inside the catch block using instanceof, like so:
} catch (Exception e) {
dialog.dismiss();
String errorMessage = getString(R.string.default_error);
if (e instanceof ArrayIndexOutOfBoundsException)
errorMessage = getString(R.string.bad_host);
else if (e instanceof UnknownHostException)
errorMessage = getString(R.string.unknown_host);
else if (e instanceof NumberFormatException)
errorMessage = getString(R.string.bad_port);
else if (e instanceof IOException)
errorMessage = getString(R.string.no_connection);
showError(errorMessage);
onDisconnect();
}
The other option is to catch all of them separately, like so:
} catch (ArrayIndexOutOfBoundsException e) {
dialog.dismiss();
showError(getString(R.string.bad_host));
onDisconnect();
} catch (UnknownHostException e)
dialog.dismiss();
showError(getString(R.string.unknown_host));
onDisconnect();
} // ...etc.
Is there a preferred way to do this? I opted for the first case (at least for now) because it minimizes duplicated code, but I've also heard that instanceof and catch (Exception) are the works of Satan.

My preference is to have a separate method like this:
void handleException(String msg) {
dialog.dismiss();
showError(getString(msg));
onDisconnect();
}
and then in your code that throws the exception just like this:
} catch (ArrayIndexOutOfBoundsException e) {
handleException(getString(R.string.bad_host));
} catch (UnknownHostException e)
handleException(getString(R.string.unknown_host));
} // ...etc.

You want to catch them separately. If you catch the generic Exception, you might end up catching Exceptions that you're not expecting (that could be pushed up from somewhere else in the stack for example) and you're stopping them from propagating up to wherever they were actually meant to be handled.
(Later edit): You may also want to look into using finally to avoid some of the code repetition problem.

make a (private void) method for handling the error. You may be required to pass it in some parameters about what's going on, but the behavior will be consistent. When you make a change to the method it changes all places where it's used, so you get to reduce your boilerplate code.
try {
// stuff
} catch(OneException) {
handleSimilarExceptions();
} catch(TwoException) {
handleSimilarExceptions();
} catch(DifferentException) {
log.write("Something wierd happened, handling it");
somethingDifferent();
}

What if you do smth like modified second version:
catch (ArrayIndexOutOfBoundsException e) {
handleException(R.string.bad_host);
} catch (UnknownHostException e)
handleException(R.string.unknown_host);
} // ...etc.
void handleException(String s) {
dialog.dismiss();
showError(getString(s));
onDisconnect();
}
And I agree, instanceof usage like this is a work of Satan...

Related

Multiple Catch blocks vs Catching in Base Exception class

Assuming we are talking about all the exceptions that extends base Exception class,
is:
try {
some code;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
catch (MyOwnException e)
{
e.printStackTrace();
}
same as:
try {
some code;
}
catch (Exception e) {
e.printStackTrace();
}
I am wondering in which case I MUST use the former one?
In the 2nd option Exception will catch all exception, not only those explicitly listed in the first option.
Use the 1st option if you want to catch only selected exceptions, and respond differently to each.
If you want to catch only selected exceptions, and have the same response to all of them, you could use:
catch (InterruptedException | ExecutionException | MyOwnException e)
{
e.printStackTrace();
}
It is good practice to use Exception sub classes rather than Exception class. If you use Exception then it would be difficult to debug.
Here is a link for reference
http://howtodoinjava.com/best-practices/java-exception-handling-best-practices/#3
If you have multiple exceptions which all are extending from...we'll say IndexOutOfBoundsException, then unless you specifically want to print a different message for StringIndexOutOfBoundsException or another sub-class you should catch an IndexOutOfBoundsException. On the other hand if you have multiple exceptions extending from the Exception class, it is proper format to create a multi-catch statement at least in JDK 1.8:
try {
// Stuff
}catch(InterruptedException | ClassNotFoundException | IOException ex) {
ex.printStackTrace();
}
The former one where you create multiple catch statements is if you were trying to do what I said before.
try {
// Stuff
}catch(StringIndexOutOfBoundsException se) {
System.err.println("String index out of bounds!");
}catch(ArrayIndexOutOfBoundsException ae) {
System.err.println("Array index out of bounds!");
}catch(IndexOutOfBoundsException e) {
System.err.println("Index out of bounds!");
}

In a Try block, is it better to create one Catch for multiple exceptions OR one Catch for each exception?

I am curious which one is more practical, and which cases do we need to use the first and where we need to use the second? For example in Java7:
first.java
try {
/* some code that throws these exceptions */
} catch (NoSuchAuthorityCodeException e) {
throw new MyAPIException("Something went wrong", e);
} catch (FactoryException e) {
throw new MyAPIException("Something went wrong", e);
} catch (MismatchedDimensionException e) {
throw new MyAPIException("Something went wrong", e);
} catch (TransformException e) {
throw new MyAPIException("Something went wrong", e);
}
second.java
try {
/* some code that throws these exceptions */
} catch (NoSuchAuthorityCodeException | FactoryException| MismatchedDimensionException | TransformException e) {
/*handle all exceptions*/;
}
Do you need to handle each exception differently? If yes, have different catch blocks with different behaviors. If you want to handle all the exceptions in the same way, one catch block is fine.
Perfectly answered by TangledUpInBlue, If only you need to handle it differently and want different actions on different types of actions, use individual catches.
Otherwise use the parent class Exception, one for all:
try{
}
catch(Exception e){
}

Catching non thrown checked exception

I have a code that invokes an external API via EJB and that API occasionally leaks an exception that is not part of the client kit, therefore resulting in ClassNotFoundException.
I have a try-catch block surrounding the call:
try {
thirdPartyLibrary.finalInvokeMethod();
} catch (SomeException exception) {
//Do something
} catch(
..
} catch (Exception exception) {
if (exception instanceof ClassNotFoundException) {
log.error("....");
}
}
I want to avoid using instanceof in catch, but if I add a separate catch clause for ClassNotFoundException, the compiler produces an error "Unreachable catch block", since thirdPartyLibrary.finalInvokeMethod(); doesn't throw ClassNotFoundException.
Is there a better way to address the issue?
I've found a workaround. I've wrapped the thirdPartyLibrary.finalInvokeMethod(); in another method that throws the checked exception. So I got a dedicated catch clause without a compiler error.
private someMethod() {
try {
callExternalAPI();
} catch (SomeException exception) {
//Do something
} catch(
..
} catch (ClassNotFoundException exception) {
log.error("....");
//Do something
} catch (Exception exception) {
//Do something
}
}
private void callExternalAPI() throws ClassNotFoundException {
thirdPartyLibrary.finalInvokeMethod();
}

Java Do X IF catch was not called from a try loop

Not sure if this has already been answered, but.
I know that in java there is the try, catch and finally blocks, but is there one which is only called if try has no errors/exceptions?
Currently after stating the command that needs to be run, I'm setting a boolean to true, and after the try and catch block, the program checks for if the boolean is true.
I'm pretty sure that there is a much simpler way, help is appreciated!
Just put your code after the try...catch block and return in the catch:
boolean example() {
try {
//dostuff
} catch (Exception ex) {
return false;
}
return true;
}
This would also work if you put the return true at the end of the try block as the code would jump to the catch on error and not execute the rest of the try.
void example() {
try {
//do some stuff that may throw an exception
//do stuff that should only be done if no exception is thrown
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
No, there is no block called only if no exceptions were raised.
The catch block is called if there were exceptions, finally is called regardless.
As stated, you can emulate such a beast with something like:
bool completed = false;
try {
doSomeStuff();
completed = true;
} catch (Exception ex) {
handleException();
} finally {
regularFinallyHandling();
if (completed) {
thisIsTheThingYouWant();
}
}
but there's nothing built into the language itself that provides this functionality.

How to manage catches with the same behavior

I have a piece of code that can throw three different types of exceptions. Two of these exceptions are handled in a certain way while the third is handled in another way. Is there a good idiom for not cutting and pasting in this manner?
What I would like to do is:
try { anObject.dangerousMethod(); }
catch {AException OR BException e) { /*do something*/ }
catch {CException e) { /*do something else*/ }
There is in JDK 7, but not in earlier Java versions. In JDK 7 your code could look like this:
try { anObject.dangerousMethod(); }
catch {AException | BException e) { /*do something*/ }
catch {CException e) { /*do something else*/ }
As defined by new Java 7 specifications you can now have.
try { anObject.dangerousMethod(); }
catch {AException | BException e) { /*do something*/ }
catch {CException e) { /*do something else*/ }
Java 6 doesn't support specifying catch blocks this way. Your best bet would be to define a super-class/interface for those two exception types and catch the super-class/interface. Another simple solution would be to have a method which contains the logic for handling those two exceptions and call that method in the two catch blocks.
How about defining a custom Exception (let's say DException) that extends both AException and BException, then use it in your code:
try { anObject.dangerousMethod(); }
catch {DException e) { /*do something*/ }
catch {CException e) { /*do something else*/ }

Categories

Resources