Computer Science

Java Finally

Java Finally is a block of code that is used in Java programming to ensure that a specific set of instructions are executed regardless of whether an exception is thrown or not. It is typically used to release resources that were acquired during the execution of a program.

Written by Perlego with AI-assistance

5 Key excerpts on "Java Finally"

  • 100+ Solutions in Java - 2nd Edition
    eBook - ePub

    100+ Solutions in Java - 2nd Edition

    Everything you need to know to develop Java applications (English Edition)

    finally block is always executed irrespective of whether an exception occurs or not. It is mainly used to execute cleanup code such as closing database connections, file streams, and so on. to avoid resource leaks.
    The finally block may not execute under the following conditions:
    If the JVM exits while executing the try or catch block.
    If a thread executing the try or catch block gets interrupted or killed.
    Syntax: try{ // statement(s) that may raise exception // statement 1 // statement 2 } catch(<exception-type> <object-name>){ // handling exception } finally{ // clean-up code }
    The following example shows the use of try-catch-finally blocks for handling Java exceptions:
    import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter first number"); int num1 = s.nextInt(); System.out.println("Enter second number"); int num2 = s.nextInt(); Calculator obj = new Calculator(); obj.calculate(num1, num2); } public void calculate(int a, int b){ try{ int c = a/b; // line 1 System.out.println("Division of "+a+" and "+b+ " is "+ c); int arr[]= new int[c]; for(int i=0;i<=arr.length;i++){ // line 2 arr[i]=i+1; } }catch(ArithmeticException e){ System.out.println("Exception occurred: "+ e.getMessage()); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception occurred: "+ e); } finally{ System.out.println("----------------------"); System.out.println("All resources closed in finally block"); } } }
    The calculate method contains two statements commented as line 1 and line 2 that can cause an exception. The statement in line 1 can raise an ArithmeticException if the user specifies zero as the value of parameter b which is the denominator. In line 2, the loop is iterating till the size of the array which can lead to ArrayIndexOutOfBounds exception. Therefore, two catch blocks have been provided to handle the two exceptions. Also, a finally
  • Creating Components
    eBook - ePub

    Creating Components

    Object Oriented, Concurrent, and Distributed Computing in Java

    Exhibit 10 (Program6.6) shows how this is done. If no exception occurs, the code in the finally block is executed. If an exception occurs and is caught, the code in the finally block is executed. If an exception occurs but is not caught, the code in the finally block is executed. Even if an attempt is made to get around the finally block by using a return statement, the finally block is executed. The finally block is always executed.

    6.5 Checked and Unchecked Exceptions

    In Java programs some exceptions have to be explicitly handled and some exceptions do not have to be explicitly handled. This is often confusing to programmers unfamiliar with Java exceptions. The rationale for this behavior is that some exceptions and errors can almost always occur, and when programmers acknowledge this reality in the code the program becomes unwieldy without producing any positive effect. However, some errors, such as trying to open a nonexistent file, are sufficiently limited in scope and important enough to require the programmer to acknowledge that they might occur and to make allowances for them.
    Exhibit 10. Program6.6: Finally Block
    The tradeoff between programmers acknowledging and specifically handling all errors or handling only a limited number of important errors is a very nice feature of Java. Some programmers react badly to a language forcing them to acknowledge anything, and they often write programs such the one shown in Exhibit 3 (Program6.3) out of ignorance, haste, or a simple refusal to handle errors. Java programs are much safer because the types of errors that occur in Exhibit 3 (Program6.3) must be explicitly handled or propagated, or their not being handled must at least be acknowledged. This is shown in Exhibit 11 (Program6.7), which shows the Java program equivalent to Exhibit 3 (Program6.3). Note that the exceptions for opening and writing to a file cannot simply be ignored in the program, so the program will produce a correct error if any problems are encountered.
    Exhibit 11. Program6.7: Java Program Equivalent to C Exhibit 3 (Program6.3)

    6.5.1 Exception Hierarchy

    Exceptions that are limited as to where they can occur and thus are handled in a program are referred to as checked exceptions. Exceptions that do not have to be handled are called unchecked exceptions. To understand the difference between checked and unchecked exceptions it is necessary to understand how Java groups exceptions and errors. Exhibit 12
  • Introduction to Java Programming, 2nd Edition
    try block exists in it.
     
    If the finally clause exists in a program, it will be executed after the try /catch block, but before the statements that follow the try /catch block. The main advantage of using this clause is that the code given inside it gets executed irrespective of occurrence of an exception. The syntax for using the finally clause is as follows:
      finally {
    //Statements to be executed
    }  
    The finally clause is optional and if it is used with the try block, it will be placed after the last catch block that is associated with that particular try block, as shown in the following code:
      try {
    //Statements
    } catch(ExceptionType obj) {
    //Statements
    } catch(ExceptionType obj) {
    //Statements
    } finally {
    //Statements
    }  
    But, if there is no catch block associated with the try block, the finally clause is placed immediately after the try block, as given next:
      try {
    //Statements
    } finally( ) {
    //Statements
    }
    Example 6
     
    The following example illustrates the use of the finally clause. The program will calculate the square of a number that will be passed as a command-line argument by the user. Also, this program will handle the exception using the try - catch - finally mechanism and display a message on the screen.
      //Write a program to calculate the square of a number and also to handle an exception 1class finally_demo 2{
    3 public static int sqr(int n)
    4 {
    5 try
    6 {
    7 int result = n*n;
    8 if(result ==0)
    9 {
    10 throw new ArithmeticException(“demo”);
    11 }
    12 else
    13 {
    14 return result;
    15 }
    16 }
    17 finally
    18 {
    19 System.out.println(“Inside the finally block”);
    20 }
    21 }
    22 public static void main(String arg[ ])
    23 {
    24 int sq;
    25
  • OCA Java SE 7 Programmer I Certification Guide
    When you work with exception handlers, you often hear the terms try, catch, and finally. Before you start to work with these concepts, I’ll answer three simple questions:
    • Try what? First you try to execute your code. If it doesn’t execute as planned, you handle the exceptional conditions using a catch block.
    • Catch what? You catch the exceptional event arising from the code enclosed within the try block and handle the event by defining appropriate exception handlers.
    • What does finally do? Finally, you execute a set of code, in all conditions, regardless of whether the code in the try block throws any exceptions.
    Let’s compare a try-catch-finally block with a real-life example. Imagine you’re going river rafting on your vacation. Your instructor informs you that while rafting, you might fall off the raft into the river while crossing the rapids. In such a condition, you should try to use your oar or the rope thrown toward you to get back into the raft. You might also drop your oar into the river while rowing your raft. In such a condition, you should not panic and should stay seated. Whatever happens, you’re paying for this adventure sport.
    Compare this to Java code:
    • You can compare river rafting to a class whose methods might throw exceptions.
    • Crossing the rapids and rowing a raft are methods that might throw exceptions.
    • Falling off the raft and dropping your oar are the exceptions.
    • The steps for getting back into the raft and not panicking are the exception handlers—code that executes when an exception arises.
    • The fact that you pay for the sport, whether you stay in the boat or not, can be compared to the finally block.
    Let’s implement the previous real-life examples by defining appropriate classes and methods. To start with, here are two barebones exception classes—FallInRiver-Exception and DropOarException—that can be thrown by methods in the class RiverRafting:
  • OCA Java SE 8 Programmer I Certification Guide
    Errors are serious exceptions thrown by the JVM, such as when it runs out of stack memory or can’t find the definition of a class. You shouldn’t define code to handle errors. You should instead let the JVM handle the errors.
    In the remainder of this section, we’ll look at some frequently asked questions on try-catch-finally blocks that often overwhelm certification aspirants.
    7.4.5. Will a finally block execute even if the catch block defines a return statement?
    Imagine the following scenario: a guy promises to buy diamonds for his girlfriend and treat her to coffee. The girl inquires about what will happen if he meets with an exceptional condition during the diamond purchase, such as inadequate funds. To the girl’s disappointment, the boy replies that he’ll still treat her to coffee.
    You can compare the try block to the purchase of diamonds and the finally block to the coffee treat. The girl gets the coffee treat regardless of whether the boy successfully purchases the diamonds. Figure 7.13 shows this conversation.
    Figure 7.13. A little humor to help you remember that a finally block executes regardless of whether an exception is thrown
    It’s interesting to note that a finally block will execute even if the code in the try block or any of the catch blocks defines a return statement. Examine the code in figure 7.14 and its output, and note when the class ReturnFromCatchBlock is unable to open file.txt.
    Figure 7.14. The finally block executes even if an exception handler defines a return statement.
    As you can see from figure 7.14 ’s code output, the flow of control doesn’t return to the method main when the return statement executes in the catch handler of FileNotFoundException. It continues with the execution of the finally block before control is transferred back to the main method. Note that control isn’t transferred to the println statement "Next task.. " that follows the try block because the return statement is encountered in the catch block, as mentioned previously.
    Going back to the example of the guy and his girlfriend, a few tragic conditions, such as an earthquake or tornado, can cancel the coffee treat. Similarly, there are a few scenarios in Java in which a finally block does not execute:
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.