

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Questions & Answers
- 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?
- Does finally always execute in Java?
- Can finally block be used without catch 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?
- Java static block
- final, finally and finalize in Java
- instance initializer block in Java
- The Initializer Block in Java
- How Does a Message Authentication Code Work?
- How does asynchronous code work in JavaScript?
Advertisements