try { //Protected code }catch(ExceptionName e1) { //Catch block }
Exception Handling in Java
It is a powerful feature provided in Java. It is a mechanism to handle run-time errors, so that the normal flow of the program is maintained.
Exception handling consists of the following five keywords:
try block
Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally block.
Syntax of try with catch block
try{ ... }catch(Exception_class_Name reference){}
Syntax of try with finally block
try{ ... }finally{}
catch block
Catch block is used to handle the Exception. It must be used after the try block.
Code without exception handling:
class App{ public static void main(String args[]){ int index = 10/0; System.out.println("another code here"); } }
As displayed in the above example, rest of the code is not executed i.e. another code here statement is not printed. Let’s see what happens behind the scene:
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.
Code with exception handling:
class App{ public static void main(String args[]){ try{ int index = 10/0; }catch(ArithmeticException e){ System.out.println(e); } System.out.println("another code here"); } }
Now, as displayed in the above example, rest of the code is executed i.e. another code here. statement is printed.
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…