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?
All methods in the call stack between the method throwing the exception and the method catching it have their execution stopped at the point in the code where the exception is thrown or propagated.
Java try and catch The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.
In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.
No, because the more specific exception (NumberFormatException) will be handleded in the first catch. It is important to note that if you swap the caches you will get a compilation error, since you MUST especify 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:
try {
// code that can throw exceptions...
} catch ( Exception1 | Exception2 | ExceptionN exc ) {
// you can handle Exception1, 2 and N in the same way here
} catch ( Exception exc ) {
// here you handle the rest
}
If a NumberFormatException
is thrown, it will be caught by the first catch
and the second catch
won't be executed. All other exceptions go to the second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With