Q1- Why would it? The finally block has nothing to do with this question, by the way.
Q2- It's telling you exactly why. If you return from both a try and catch block, how will you ever reach the code after the try/catch?
Kevin Workman wrote:Q1- Why would it? The finally block has nothing to do with this question, by the way.
Q2- It's telling you exactly why. If you return from both a try and catch block, how will you ever reach the code after the try/catch?
Hi Kevin,I changed the code and trying to understand the concept behind for these 2 points. Please advice
In the following case:
Would you expect "Hello World" to be printed? No - the method returns before you get there. It's the same in the example you've given. return exits the method, not the block it's in.
Firstly, the code won't compile. You can't return a value from a void method.
Secondly, dude if you put a return in a try and a catch, how will you ever reach "After finally"?
And, I still don't understand why "After finally" is not being printed. It should, because once the exception is caught and dealt with, shouldn't it move on to the next line of code?
Mathew Brown, the compiler doesn't know that i is actually < 20. But the compiler knows in the previous example that the code below won't ever be reached.
Rohit Ramachandran wrote:And, I still don't understand why "After finally" is not being printed. It should, because once the exception is caught and dealt with, shouldn't it move on to the next line of code?
Yes, the exception is caught and dealt with, but note the return statement in the catch block. Meaning that after the exception is dealt with (and the finally block is executed), the method returns.
Dude, at line 3, the code can either reach the try part and then the catch part of the try/catch block. In both cases, you've put a return so there's no way you'll ever get to line 10. THe error says clearly, "Unreachable code"
The compiler pretty much strips your catch block, and inlines it, because it sees that you will always throw an exception. It pretty much does this:So it sees that your last line will *never* be run.
Because you have a "throw" in the try part of the try/catch block, which means each time the try block is entered, it ends up in the catch block. The compiler knows this.
Just modify the code to this-
Hello World is still unreachable but you won't get the unreachable code error since the compiler doesn't know that x=5/0 will throw an ArithmeticException: divide by zero.