What is a finally block? When and how is it used? Give an example.
Long Answer
Views 45
Answer:
-
The
finallyblock is a block of code that always executes, whether or not an exception occurs. -
It is mainly used to release resources such as files, database connections, or network sockets.
Syntax:
try { // Code that may throw exception } catch (Exception e) { // Handle exception } finally { // Code that always executes }
Example:
import java.io.*; public class FinallyExample { public static void main(String args[]) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("MyFile.java")); System.out.println("Reading file..."); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } finally { System.out.println("Finally block executed. Closing reader."); try { if(reader != null) reader.close(); } catch (IOException e) { System.out.println("Error closing reader"); } } } }
Output:
Error: MyFile.java (No such file or directory) Finally block executed. Closing reader.
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.