Developer community
0 votes
1.4k views
asked by Geek (15.3k points) 17 42 62 | 1.4k views

2 Answers

0 votes
Finally is the block of code that executes always. The code in finally block will execute even if anexception is occurred. finally will not execute when the user calls System.exit().
answered by Guru (39.1k points) 10 22 35
0 votes
finally creates a block of code that will be executed after a try/catch block has completed.
 
The finally block will execute even if no catch statement matches the exception.
 
finally block can be useful for closing file handles and freeing up any other resources. The finally clause is optional.
 
Example
 
public class Main {
  // Through an exception out of the method.
  static void methodC() {
    try {
      System.out.println("inside methodC");
      throw new RuntimeException("demo");
    } finally {
      System.out.println("methodC finally");
    }
  }
 
  // Return from within a try block.
  static void methodB() {
    try {
      System.out.println("inside methodB");
      return;
    } finally {
      System.out.println("methodB finally");
    }
  }
 
  // Execute a try block normally.
  static void methodA() {
    try {
      System.out.println("inside methodA");
    } finally {
      System.out.println("methodA finally");
    }
  }
 
  public static void main(String args[]) {
    try {
      methodC();
    } catch (Exception e) {
      System.out.println("Exception caught");
    }
    methodB();
    methodA();
  }
}
 
 
answered by Advisor (8.4k points) 10 15 18

Related questions

0 votes
2 answers
asked by john Guru (27.1k points) 33 50 100 | 31 views
0 votes
1 answer
asked by felin Advisor (8.4k points) 10 15 18 | 915 views
0 votes
1 answer
asked by john Guru (27.1k points) 33 50 100 | 8 views
0 votes
1 answer
asked by smith Geek (15.3k points) 17 42 62 | 11 views
0 votes
1 answer
asked by felin Advisor (8.4k points) 10 15 18 | 9 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users