I want to use a try-catch block to handle two cases: a specific exception, and any other exception. Can I do this? (An example)
try{
Integer.parseInt(args[1])
}
catch (NumberFormatException e){
// Catch a number format exception and handle the argument as a string
}
catch (Exception e){
// Catch all other exceptions and do something else. In this case
// we may get an IndexOutOfBoundsException.
// We specifically don't want to handle NumberFormatException here
}
Will the NumberFormatException be handled by the bottom block as well?
No, because the more specific exception (NumberFormatException) will be handled in the first catch. It is important to note that if you swap the catches you will get a compilation error, since you MUST specify the more specific exceptions before the more general ones.
It is not your case, but since Java 7 you can group exceptions in catch like: