This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Originally posted by Shiaber Shaam: My doubt is exactly like.. * Whenever the remining code in the try block after the code causing exception will get executed...
In this example, never.
An exception says, "There's something wrong here that's preventing me from continuing with this code." So instead of trying to move forward, an exception is thrown and control is passed outside the try block. It's like taking an alternate route when a "Road Closed" sign unexpectedly appears on the path you're following.
The catch and finally blocks can provide a graceful exit so that the program doesn't just crash.
If you wanted to try the code again, you would need to recall the method from inside the catch or finally block. But if you're able to code a process for recovering from the exception, then this probably should have been built into the code in the first place, avoiding an exception entirely.
In your code, the exception is always thrown, so the "Road Closed" sign is not unexpected, and the compiler tells you that this path can never be taken. As suggested above, you could change this by making the exception a chance occurrence. For example, in the code below, an exception might or might not be thrown, depending on nextBoolean(). But each time an exception is thrown, the method is recalled. This continues until the code executes without an exception.
[ February 20, 2007: Message edited by: marc weber ]