In this course, we will learn the concepts of microservice and spring framework and focus on Exception Handling.
Learning Objectives
- Exception Handling in Java
Intended Audience
- Beginner Java developers
- Java developers interested in learning how to Build and Deploy RESTful Web Services
- Java Developers who want to develop web applications using the Spring framework
- Java Developers who want to develop web applications with microservices
- Java Developers who wish to develop Spring Boot Microservices with Spring Cloud
Prerequisites
- Basic Java knowledge
Hello there. In this video, we will 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 block. 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 the finally block is executed again.
To help understand better, let's go through an example using exception handling. To begin, let us create a new Java project and name it ExceptionHandling. Don't change the other options and click the 'Finish' button. 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 will create a small program that does a simple mathematical operation. For this, I will declare three variables with int type. First, number1 and assign 0. Second, number2 and assign 0. And last, result, assign 0. Now, I will use the Scanner class to get input from the user. Scanner. To use the Scanner class, we will import the Scanner class in the java.util package.
The name of the object can be input, input = new Scanner(system.in). Now, I will show a message to enter the first int number by using the print() method. S.out ("Please enter the first in number: ") and assign the next int method of Scanner class to variable number1, numbe1 = input.nextInt(). Again I'll show another message to enter the second int number by using the print() method. Sout ("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. S.out ("Result: " + result). Finally, we should close the Scanner object by using the close() method. Let's run the code. In the console screen, I will enter 12 for the first number and two for the second number. The result is six. There's 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 input mismatch exception and the program was terminated. The next int method could not read that as an integer and threw an input mismatch exception object. The second print() method message, "Enter second int number" was not executed. We want to catch this error and display our message on the console. We do it by using try, catch, and finally blocks. The try block encloses the code which may throw exceptions. Let's enclose the code that may throw an exception with the try-catch block. An input mismatch exception might be thrown here, 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 exception 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 will display the "Please enter valid number" message by using the print() method.
Okay, let's run the code again. On th e 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 will 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 will 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 will 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 "The second number cannot be 0" message is displayed. In addition, if any exception occurs except these two exceptions, we can use the superclass 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 a 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 use the print() method to show the message, "The statement is always run." Let's run the code again. On the console screen, I will enter 12 for the first number and two for the second number. The result is six 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 will enter Java for the first number. As you can see, the related catch block handles the exception and the "Please enter valid number" message is displayed. Also, the finally block is executed again and the "This statement is always executed" message is displayed. 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 the code that we want to run in any case, it makes sense to use it in the finally block. I think you guys understand 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 an error. I will create a do while loop here. And I will move these codes into the do block. I need to check this loop with a condition. For this, first I will declare a variable, isFlag, with a Boolean type. Its initial value will be false. We use the variable isFlag in the while condition. This loop is repeated until isFlag is true. After the code prints the result, we set the variable isFlag to true. 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 the variable is set to true and the while loop will be terminated.
Okay, let's run the code again. I will enter Java for the first number. And the first catch block handles the exception and the "Please enter valid number" message is displayed. Also, the finally block message is displayed, and so the loop continues and asks us to enter the first number because the variable isFlag is still false. This time I will 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 0" message is displayed. Also, the finally block message is displayed, and so the loop continues and asks us to enter the first number because the variable isFlag is still false. This time I will enter 12 for the first number and four for the second number. The result is three. Division operation is done successfully, and this time the variable isFlag is set true, and finally block message is displayed and the loop terminates because the value of variable isFlag is true. Okay, I think we got it all. So, let's take a short break here. I'll see you in the next video friends.
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.