Java try...catch...finally
In Java, the try-catch-finally
block is a mechanism for handling exceptions that occur during program execution, and for executing code that should always be run regardless of whether an exception is thrown or not.
The syntax for a try-catch-finally
block is as follows:
try { // code that may throw an exception } catch (ExceptionType1 ex1) { // code to handle exception of type ExceptionType1 } catch (ExceptionType2 ex2) { // code to handle exception of type ExceptionType2 } finally { // code to execute whether an exception was thrown or not }
In this example, the try
block contains the code that may throw an exception. The catch
block(s) contain the code that will be executed if an exception of the specified type is thrown. If an exception is thrown that is not caught by any of the catch
blocks, it is propagated up the call stack.
The finally
block is optional and contains code that will be executed regardless of whether an exception was thrown or not. This is useful for performing cleanup operations, such as closing files or releasing resources. The finally
block is always executed, even if there is a return
statement in the try
or catch
blocks.
Here's an example of a try-catch-finally
block in action:
FileInputStream file = null; try { file = new FileInputStream("file.txt"); // code that reads from the file } catch (FileNotFoundException ex) { System.out.println("Error: file not found."); } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); } finally { if (file != null) { try { file.close(); // close the file } catch (IOException ex) { System.out.println("Error closing file: " + ex.getMessage()); } } System.out.println("This code will always execute."); }
In this example, we're trying to open a file and read from it. If the file is not found, a FileNotFoundException
will be thrown and caught by the first catch
block. If an IO error occurs while reading the file, an IOException
will be thrown and caught by the second catch
block.
In the finally
block, we're checking whether the FileInputStream
object is null
, and if not, closing the file. The finally
block also contains a print statement that will always execute.