Java finally blockJava finally block is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block. Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).Why use java finally
Usage of Java finallyLet's see the different cases where java finally block can be used. Case 1Let's see the java finally example where exception doesn't occur. Output:5 finally block is always executed rest of the code... Case 2Let's see the java finally example where exception occurs and not handled. Output:finally block is always executed Exception in thread main java.lang.ArithmeticException:/ by zero Case 3Let's see the java finally example where exception occurs and handled. Output:Exception in thread main java.lang.ArithmeticException:/ by zero finally block is always executed rest of the code... Rule: For each try block there can be zero or more catch blocks, but only one finally block.Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort). Next TopicJava Throw Keyword
|