Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Program to Use finally block for Catching Exceptions
Next article icon

Java Program to Use finally block for Catching Exceptions

Last Updated : 27 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.

There are 3 possible cases where finally block can be used:

Case 1: When an exception does not rise 

In this case, the program runs fine without throwing any exception and finally block execute after the try block.

Java
// Java program to demonstrate // finally block in java When // exception does not rise   import java.io.*;  class GFG {     public static void main(String[] args)     {         try {             System.out.println("inside try block");                        // Not throw any exception             System.out.println(34 / 2);         }                // Not execute in this case         catch (ArithmeticException e) {                        System.out.println("Arithmetic Exception");                    }         // Always execute         finally {                        System.out.println(                 "finally : i execute always.");                    }     } } 

Output
inside try block  17  finally : i execute always.

Case 2: When the exception rises and handled by the catch block

In this case, the program throws an exception but handled by the catch block, and finally block executes after the catch block.

Java
// Java program to demonstrate finally block in java // When exception rise and handled by catch  import java.io.*;  class GFG {        public static void main(String[] args)     {         try {             System.out.println("inside try block");              // Throw an Arithmetic exception             System.out.println(34 / 0);         }          // catch an Arithmetic exception         catch (ArithmeticException e) {              System.out.println(                 "catch : exception handled.");         }          // Always execute         finally {                        System.out.println("finally : i execute always.");         }     } } 

Output
inside try block  catch : exception handled.  finally : i execute always.

Case 3: When exception rise and not handled by the catch block 

In this case, the program throws an exception but not handled by catch so finally block execute after the try block and after the execution of finally block program terminate abnormally, But finally block execute fine.

Java
// Java program to demonstrate finally block  // When exception rise and not handled by catch  import java.io.*;  class GFG {     public static void main(String[] args)     {         try {             System.out.println("Inside try block");              // Throw an Arithmetic exception             System.out.println(34 / 0);         }          // Can not accept Arithmetic type exception         // Only accept Null Pointer type Exception         catch (NullPointerException e) {              System.out.println(                 "catch : exception not handled.");         }          // Always execute         finally {              System.out.println(                 "finally : i will execute always.");         }         // This will not execute         System.out.println("i want to run");     } } 

Output

Inside try block  finally : i will execute always.  Exception in thread "main" java.lang.ArithmeticException: / by zero      at GFG.main(File.java:10)

Next Article
Java Program to Use finally block for Catching Exceptions

N

nikhilchhipa9
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-Exception Handling
Practice Tags :
  • Java

Similar Reads

    Java Program to Handle Checked Exception
    Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error.  ClassNotFoundExcept
    5 min read
    Java Program to Handle Unchecked Exception
    Exceptions are the issues arising at the runtime resulting in an abrupt flow of working of the program. Remember exceptions are never thrown at the compile-time rather always at runtime be it of any type. No exception is thrown at compile time. Throwable Is super-class of all exceptions and errors t
    4 min read
    Using throw, catch and instanceof to handle Exceptions in Java
    Prerequisite : Try-Catch Block in Java In Java, it is possible that your program may encounter exceptions, for which the language provides try-catch statements to handle them. However, there is a possibility that the piece of code enclosed inside the 'try' block may be vulnerable to more than one ex
    4 min read
    Java Program to Use Exceptions with Thread
    Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. When a method encounters an abnormal condition that it can not handle, an exception is thrown as an exception statement. Exceptions are caught
    5 min read
    Java Program to Handle Runtime Exceptions
    RuntimeException is the superclass of all classes that exceptions are thrown during the normal operation of the Java VM (Virtual Machine). The RuntimeException and its subclasses are unchecked exceptions. The most common exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ClassCastE
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences