Finally Block

Start course
Overview
Difficulty
Beginner
Duration
50m
Students
24
Description

In this course, we'll learn about Exception Handling in Java.

Learning Objectives

  • What is an Exception?
  • Difference between Error and Exception
  • Types of Exceptions
  • Try-Catch Block
  • Finally Block
  • Throw and Throws Keywords
  • Exception Methods

Intended Audience

  • Anyone looking to get Oracle Java Certification
  • Those who want to learn the Java Programming language from scratch
  • Java developers who want to increase their knowledge
  • Beginners with no previous coding experience in Java programming
  • Those who want to learn tips and tricks in Oracle Certified Associate – Java SE 8 Programmer certification exams

Prerequisites

  • No prior knowledge is required about the Java programming language
  • Basic computer knowledge
Transcript

Hi there. In this video, we'll talk about the Finally Block. The finally block in Java is used to execute important code, such as closing connection, stream etc. If an exception occurs in the program, the currently executing method may stop without completing execution. In this situation, some codes such as closing connections will never get called. Java provides the finally block to deal with these situations. The finally block is always executed whether an exception is handled or not and the finally block follows the try or catch block. The finally block is optional. This block is placed after the last catch blocks. As you see in the diagram, firstly, try block is executed. 

If code in the try block throws an exception, the catch block is executed and finally block is executed. If code in the try block does not throw an exception, again, finally block is executed. Okay, let's make some examples with exception handling to understand clearly. First, let's create a new Java project and specify the project name as ExceptionHandling. The Java version will be Java 1.8 or Java.8. Don't change the other options and click the 'Finish' button. Okay, in this project, right click on the source folder and select new class. Specify package name as Exception and class name as ExceptionHandling, and select the checkbox to add the main method and click the 'Finish' button to create this class. Okay, to understand exception in Java, we'll create a small program that does a simple mathematical operation. For this, I'll declare three variables with int type. First, number1 and assign 0. 

Second, number2 and assign 0. And last, result, assign 0. Now we'll use the Scanner class for getting input from the user. Scanner, to use the Scanner class, we will import the Scanner class in java.util package. The name of the object can be input, input = new Scanner (System.in); Okay, now I will show a message to enter the first int number by using the print method. System.out.println ("Please enter the first int number: "); and assign the next int method of Scanner class to variable number1. number1 = input.nextInt(). Again, I'll show another message to enter the second int number by using the print method. System.out.println("Please enter the second int number: "); and assign the next int method of Scanner class to variable number2. number2 = input.nextInt(). Now let's assign the number1 / number2 expression to the variable result. result = number1 / number2. And lastly, let's print the value of the variable result by using the print method. System.out.println("Result: " + result); Finally, we should close the Scanner object by using the close method. Okay, let's run the code. 

In the console screen, I will enter 12 for the first number and 2 for the second number. The result is 6. There is no problem. Let's run the code again. I will enter Java text for the first number instead of the integer number. And as you can see, after pressing the 'Enter' key, we got an exception named InputMismatchException and the program was terminated. The next int method could not read that as an integer and threw an InputMismatchException object. The second print message message "Enter second int number" was not executed. We want to catch this error and display our message to the console. We do it by using try, catch, and finally blocks. A try block encloses the code which may throw exceptions. Let's enclose the code that may throw an exception with the try-catch block. The exception that might be thrown here is an InputMismatchException, and so a catch block has been provided to handle it. I will copy InputMismatchException from the console and paste it within the parentheses following the catch keyword. And we need to import this class. We must declare an execution type object named e. 

We will use this identifier to display the error in the next exercises. Yes, if this catch block works i.e InputMismatchException occurs, let's show a message to the user. In the catch block, I'll display the "Please enter valid number" message by using the print method. Okay, let's run the code again. In the console screen, we enter Java again. As you can see, this time the program was not terminated directly when the exception was encountered, and the code we wrote in the catch block was executed. So, the try-catch block handles the exception and the "Please enter valid number" message is displayed. Let's run the code again. On the console screen, I'll enter 12 for the first number and 0 for the second number. And as you can see, we got an exception again, but this time its name is ArithmeticException. Let's handle this exception in the second catch block. 

I'll create the second catch block after the first catch block. We write ArithmeticException within the parentheses following the catch keyword. ArithmeticException class is predefined in the java.lang package so we don't need to import this class. In the catch block, we display "The second number cannot be 0" message by using the print method. Okay, let's run the code again. On the console screen, I'll enter 12 for the first number and 0 for the second number. And as you can see, this time the program was not terminated directly when the exception was encountered and the code we wrote in the second catch block was executed. So, the try-catch block handles the exception and "Second number cannot be 0" message is displayed. Okay,

in addition, if any exception occurs except those two exceptions, we can use the Super class of all exceptions named Exception to handle it. Let's handle this exception in the third catch block. I write Exception within the parentheses following the catch keyword. The exception class is predefined in the java.lang package, so we don't need to import this class. In the catch block, we display the "An exception occurred" message by using the print method. Also, we can add the finally block. Let's add finally block after the last catch block. Finally block is always executed. In the finally block, we display the "This statement is always executed" message by using the print method. Okay, let's run the code again. On the console screen, I'll enter 12 for the first number and 2 for the second number. The result is 6 and there is no exception. But if you notice, the finally block is executed and the message is displayed. Let's run the code again. On the console screen, I'll enter Java for the first number. As you can see, the related catch block handles the exception and "Please enter valid number" message is displayed. 

Also, finally block is executed again and the "This statement is always executed" message is displayed again. As a result, note that the code you write in the finally block is executed in all cases. So, why should we use the finally code block in this case? Actually, as I mentioned at the beginning of the lesson, we don't have to use the finally block, but if we have code that we want to run in any case, it makes sense to use it in the finally block. Yes, I think it's understood how exceptions occur and how to handle these exceptions with blocks. If you want, let's continue the program using a do-while loop here until the correct parameters are entered by the user. Let's finish the program when the correct parameters are entered and the result is calculated without error. I'll create a do-while loop here, and I'll move these codes into the do block. Okay, I need to check this loop with a condition. 

For this, firstly, I'll declare a variable isFlag with Boolean type. Its initial value will be false. We use the variable isFlag in the while condition. This loop continues until isFlag true. In the code, after printing the result, we assign true to the variable isFlag. If an exception occurs in the code, then the value of the variable isFlag will not be true. So, the do-while loop will continue. If there is no exception in the code, then the value of this variable is set to true and while loop will be terminated. Okay, let's run the code again. I'll enter java for the first number, and the first catch block handles the exception and the "Please enter valid number" message is displayed. 

Also, finally block message is displayed. And the loop continues and asks us to enter the first number because the variable isFlag is false. This time, I'll enter 12 for the first number and 0 for the second number, and this time the second catch block handles the exception and the "Second number cannot be zero" message is displayed. Also, finally block message is displayed, and the loop continues and asks us to enter the first number because variable isFlag is still false. This time I'll enter 12 for the first number and 4 for the second number. The result is 3. Division operation is done successfully, and this time the variable isFlag is set to true, and finally block message is displayed and the loop terminates because the value of variable isFlag is true. Yes, I think this subject is understood. Let's take a short break here. I'll see you in the next video.

 

About the Author
Students
458
Courses
47
Learning Paths
3

OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.

Covered Topics