I\'m reviewing some new code. The program has a try and a finally block only. Since the catch block is excluded, how does the try block work if it encounters an exception
Inside try
block we write codes that can throw an exception.
The catch
block is where we handle the exception.
The finally
block is always executed no matter whether exception occurs or not.
Now if we have try-finally block instead of try-catch-finally block then the exception will not be handled and after the try block instead of control going to catch block it will go to finally block. We can use try-finally block when we want to do nothing with the exception.
Regardless of exception thrown or not in try
block - finally
block will be executed. Exception would not be caught.
If any of the code in the try block can throw a checked exception, it has to appear in the throws clause of the method signature. If an unchecked exception is thrown, it's bubbled out of the method.
The finally block is always executed, whether an exception is thrown or not.
Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!
A small note on try
/finally
: The finally will always execute unless
System.exit()
is called.try{}
block never ends (e.g. endless loop).