Exceptions handling
Exceptions
Finally clause
How to use the finally clause
- The code in the finally block is executed whether or not an exception is thrown.
- If the try statement is coded in a method that returns a value to its calling method, the code in the finally block is executed even if the code in the try block or a catch block issues a return statement.
- Unlike the code in a finally block, code that follows a try statement isn't executed if an exception is thrown but not handled by one of the catch clauses.
A try statement that uses a finally clause
try { // code that throws FileNotFoundException return productFile; } catch (FileNotFoundException e) { // code that handles FileNotFoundException return null; } finally { // code that's executed whether or not // FileNotFoundException is thrown }
A try statement that doesn't use a finally clause
try { // code that throws FileNotFoundException } catch (FileNotFoundException e) { // code that handles FileNotFoundException } // code that's executed whether or not // FileNotFoundException is thrown
A try statement that uses a finally clause for an unhandled exception
try { // code that throws FileNotFoundException // or IOException } catch (FileNotFoundException e) { // code that handles FileNotFoundException } finally { // code that's executed whether or not // FileNotFoundException or IOException is thrown } // code that's executed whether or not // FileNotFoundException is thrown // but not if IOException is thrown