finally block in java
Dec 31, 2014
by
at
3:47 pm
Java Exception Handling Tutorial List :
1:Exception Handling in Java 2:try and catch block in Exception Handling 3:finally block in java 4:throw and throws keyword in java 5:How to find the details of exception in java 6:How to Create User Defined Exception Class In Java
Java finally block is always executed whether exception is handled or not.Java finally block must be followed by try or catch block.
The main usage of finally block is to releases the resources which are obtained in try block (resources are opening files, opening databases connection etc.).
Java finally block must be followed by try or catch block.
Example
public static void main(String[] args){ FileReader fileInput = null; try { //Open the input file fileInput = new FileReader("Untitled.txt"); } catch(FileNotFoundException | IOException ex) { //handle both exceptions } finally { //We must remember to close streams //Check to see if they are null in case there was an //IO error and they are never initialised if (fileInput != null) { fileInput.close(); } } }
Example code of finally block
package com.jwt.java; public class ExceptionExample { public static void main(String[] a) { /** * Exception will occur and it will caught in catch block and contol * will goto finally block. */ try { int i = 10 / 0; } catch (Exception ex) { System.out.println("Inside 1st catch Block"); } finally { System.out.println("Inside 1st finally block"); } /** * In this case exception will not occur, after executing try block the * contol will goto finally block. */ try { int i = 10 / 10; } catch (Exception ex) { System.out.println("Inside 2nd catch Block"); } finally { System.out.println("Inside 2nd finally block"); } } }
Output :
Inside 1st catch Block Inside 1st finally block Inside 2nd finally block
Related Articles