Exception Handling in Java
Exception Handling in Java is a way to tackle abnormal occurrences which interrupts the normal flow of the program.
Contents
Best-suited Java courses for you
Learn Java with these high-rated online courses
Introduction
This article goes through the details of Exception Handling in Java. It covers the exception handling mechanism, types of exceptions, and hierarchy of exception classes, along with a complete example.
Letβs begin by understanding exceptions first.
What is Exception Handling?
Exceptions are basically abnormal circumstance that occurs at runtime. Hence, to handle such an unfortunate situation, we have an exception handling mechanism.
Exception handling is a way to tackle these abnormal situations gracefully, which helps develops to debug their code easily. Moreover, it helps in maintaining the flow of code execution.
In Java, an exception is a java object which gets created when an exceptional condition occurs and disturbs the normal flow of the program. For instance, an attempt to divide a number by 0.
- The occurrence of an exception condition invokes the method to create an exception object and throws it to the java runtime system. FYI, the exception object contains the exception name, type, description, and current state of execution.
- Afterward, first, the java runtime starts searching for the exception handler in the method which created the exception object.
- Then, it searches in the calling method (usually the main method).
- In case thereβs no exception handler in the program, the java runtime terminates it. Else catches the exception.
The below diagram shows the flow of handling an exception in java.
Syntax:
try { //code to be monitored for an exception throw exception_object //throw an exception object to the Java Runtime } catch(exception_object) { //exception handler for catching the exception_object } finally { //The code will get executed in any case }
Example: Simple try-catch block usage for exception handling
class Main_class { public static void main(String[] args) { int var1 = 32; double result; try { result = var1/0; System.out.println("Result of division: " +result); } catch (ArithmeticException e) { System.out.println("Exception caught! " +e ); } }}
Output:
Explanation: The moment an exception occurs in the try block, the flow of execution jumps to the matching catch block. For the time, all the statements in between are skipped, and statements under the catch block get executed. Afterward, the control goes back to the try block and continues normal execution.
Exception Handling Keywords in Java
Following are the 5 keywords to define exception handling in Java:
Keywords | What do they do? |
---|---|
try | The statements susceptible to a runtime error fall under the try block. A try block canβt exist independently. It has to accompany by either catch or finally block. |
catch | The catch block contains the statements of action to be taken when an exception occurs in the try block. Catch used without a try block leads to a compile-time error. |
finally | This block contains a set of statements that executes whether or not an exception is thrown. |
throw | The throw keyword utilizes to throw the exception explicitly. |
throws | This keyword is used with the method prototype which indicates the type of exceptions that the method might throw to the java runtime. |
Types of Exceptions in Java
The exceptions divide into 2 categories:
Checked Exceptions: These exceptions are a must-handle. As ignorance leads to errors by the compiler. Hence, creates a compile-time error. Ex: ClassNotFoundException, IllegalAccessException, etc.
Unchecked Exceptions: These are runtime exceptions caught by the java runtime system. It is not compulsory to handle unchecked exceptions. As they are anyway handled by JVM. Ex: ArithmeticException, NullPointerException, ArrayStoreException, etc.
Hierarchy of Exceptions class in Java
All these classes are present in java.lang package.
Object class stands at the root of the Hierarchy. Throwable is the subclass of object class and serves as a superclass for Errors and Exception classes. In addition, Errors are incidents that canβt be handled. Usually, errors are created by the JVM system. On other hand, the Exception class handles the checked exceptions, Moreover, it includes the RuntimeException class to handle unchecked exceptions.
Java Exception Handling Example
class A_class{ public void callMe_Func() { //throwing exception using throw keyword throw new NullPointerException("Null Pointer Access!!"); }} class Main_class { public static void main(String[] args) { try { A_class obj = new A_class(); obj.callMe_Func(); } catch (NullPointerException e) { System.out.println("Exception caught! " +e ); } }}
Output:
In Conclusion
I hope the above article helped you build an understanding of exception handling in java. If you have any queries feel to reach us with the link below.
Also, read: Top 160 Java Interview Questions and Answers for 2022
Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.
Click here to submit its review with Shiksha Online.
FAQs
What is Java?
It is an object-oriented, dynamic, multithreaded, platform-independent, and distributed programming language which enables developers to solve real-world problems with technology.
What is an Exception?
The exception is an abnormal occurrence that disturbs the normal flow of the running program.
Name all the keywords used for Exception Handling in Java.
try, catch, finally, throw and throws.
What is the difference between exceptions and errors?
Exceptions can be resolved in the program itself. However, errors can not be handled by the code. It is usually occurred by external glitches or JVM.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio