- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Does code form Java finally block
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
- Related Articles
- Is there a case when finally block does not execute in Java?
- What is the finally block in Java?
- Is finally block always get executed in Java?
- Can finally block be used without catch in Java?
- Does finally always execute in Java?
- Explain Try/Catch/Finally block in PowerShell
- Is there any way to skip finally block even if some exception occurs in exception block using java?
- Will a finally block execute after a return statement in a method in Java?
- Does JavaScript support block scope?
- final, finally and finalize in Java
- Java static block
- What are the restrictions imposed on a static method or a static block of code in java?
- What are try, catch, finally blocks in Java?
- Difference Between Final, Finally and Finalize in Java
- instance initializer block in Java

Advertisements