
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Finally Block Explanation
The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
The return statement in the method too does not stop the finally block from getting executed.
Example
In the following Java program we are using return statement at the end of the try block still, the statements in the finally block gets executed.
public class FinallyExample { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); return; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } }
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
Only way to avoid the finally block
Still if you want to do it forcefully when an exception occurred, the only way is to call the System.exit(0) method, at the end of the catch block which is just before the finally block.
Example
public class FinallyExample { public static void main(String args[]) { int a[] = {21, 32, 65, 78}; try { System.out.println("Access element three :" + a[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); System.exit(0); } finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } }
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 5
Advertisements