Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-catch short-circuit/fall-through java

Tags:

java

exception

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?

like image 631
dmi_ Avatar asked Jul 18 '12 01:07

dmi_


People also ask

Does try catch stop execution Java?

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.

What happens in try catch Java?

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.

What happens if I put the system out in the catch 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.

Does Try Catch affect performance?

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.


2 Answers

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
}
like image 137
davidbuzatto Avatar answered Oct 19 '22 05:10

davidbuzatto


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.

like image 43
Daniel Fischer Avatar answered Oct 19 '22 05:10

Daniel Fischer