In Java, an exception is an event that disrupts the normal flow of the program. Exception handling is used to handle runtime errors so that the normal flow of the application can be maintained. It is an object which is thrown at runtime.
Exceptions in Java can arise from different kinds of situations such as wrong data entered by the user, hardware failure, network connection failure, or a database server that is down. When a failure in the code occurs, things that need to be done or performed is called exception handling. The code that specifies what to do in specific exception scenarios is explained in exception handling.
Picture Credit: https://unsplash.com/photos/G1yhU1Ej-9A
Advantage of Exception Handling
When we come across a exception in the code, the normal flow of the code is disturbed and the remaining part of the code is not executed by this exception. To overcome this exception handling can be used.
Example:
1. statement 1;
2. statement 2;
3. statement 3; //exception occurs
4. statement 4;
5. statement 5;
Let’s consider above scenario where we need to execute 5 statements and an exception occurs at stamen 3. The rest of the code consisting of statement 4 and 5 will not be executed due to error at statement 3. This problem can be addressed in Java by using exception handling. By using exception handling we can execute statement 4 & 5 even after getting error at statement 3.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Types of Java Exceptions
There are three types of exceptions namely:
Checked Exception
Unchecked Exception
Error
Difference between Checked, Unchecked Exceptions and Error:
1) Checked Exception
Checked Exceptions are checked at the compile-time. These classes directly inherit the Throwable class except Runtime Exception and Error are known as checked exceptions. Examples: IO Exception, SQL Exception, etc.
2) Unchecked Exception
Unchecked exceptions are not checked at compile time, but they are checked at runtime. The classes that inherit the Runtime Exception are known as unchecked exceptions. Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc
3) Error
An erroring the java code indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. Error is irrecoverable. Some examples of errors are OutOfMemoryError, VirtualMachineError, Assertion Error etc.
Java Exception Keywords
Below keywords are used in Java for exception handling.
Methods to print exception messages:
getMessage() — Returns the detail message string of this throwable. Returns the detail message string of this Throwable instance (which may be null).
getLocalizedMessage() — Creates a localized description of this throwable. Subclasses may override this method to produce a locale-specific message. For subclasses that do not override this method, the default implementation returns the same result as getMessage().Returns The localized description of this throwable.
getStackTrace()- Returns an array of stack trace elements, each representing one stack frame. Returns an array of stack trace elements representing the stack trace pertaining to this throwable.
Java Exception Handling Example
Whenever we write a code, we suspect that it might have exceptions. Let’s see some examples of such codes and how to handle those exceptions in java and the messages of the exceptions.
Scenario with try and catch blocks
In the below scenario I tried to create an exception by dividing an integer variable by zero which in turns throws an exception. In try block the code is written which may throw exception based on the values of the integers declared. In catch block a customized message is written to print the exception that was occurred.
Output:
The above same example is written with throw key word used in catch block. In this scenario when an exception occurs in try block the control immediately goes out of try block and catch block is executed. When executing the catch block print message is executed first and next when it reaches the throw key word, control goes out of catch block and finally block is executed which gives the output message. At last the throw exception is executed.
Output:
Scenario with multiple try, catch and finally blocks:
In the below example , I have used string operator(defined it to null) along with integers to generate more than one exception. If an exception with integers occurs, then Arithmetic exception catch block will be executed and if an exception occurs with string, then catch block with Null pointer exception will be executed. As Exception is the super method for all the exceptions, if any exceptions other then the defined occurs then the exception block will be executed.
Output:
From Java 7, multiple catch block can be executed in single catch block using pipe (|) separator. The above example is recreated using the pipe and writing the multiple catch blocks in single line. An exception in Null Pointer is created and the catch block executes it successfully.
Output:
With the same above coding, an exception in arithmetic divide by zero is created and the same catch block can handle the exception.
Output:
Conclusion:
When an unusual situation occurs in the execution of the code, exception handling gives the better way of understanding its problem and may lead to quick recorrect it. It makes the code easier to be handled and understand even for the new person who walks throws the code. BY clearly defining the exception types it’s easier to analyze the results and make necessary changes in the input or the user can act accordingly.