Exception Handling in Java
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that
is why we need to handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and
Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception cod
means we can't use try block alone. The try block must be followed by either catc
finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block w
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is exec
whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occu
exception in the method. It doesn't throw an exception. It is always used with met
signature.
JavaExceptionExample.java
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled
by a try-catch block.
If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try block
that will not throw an exception.
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw an exception
3. }finally{}
The catch block must be used after the try block only. You can use multiple catch
block with a single try block.
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
finally block
Java finally block is a block used to execute important code such as closing the
connection, etc.
Note: If you don't handle the exception, before terminating the program, JVM executes
finally block (if any).
o finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
o The important statements to be printed can be placed in the finally block.
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }
Output:
Java throw Exception
In Java, exceptions allows us to write good quality codes where the errors are
checked at the compile time instead of runtime and we can create custom exceptions
making the code recovery and debugging easier.
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related
to user inputs, server, etc.
We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw ArithmeticException if we divide a
number by another number. Here, we just need to set the condition and throw
exception using throw keyword.
TestThrow1.java
In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.
Output:
The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the exception
or declare in throws clause.
Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as NullPointerException, it is programmers' fault that
he is not checking the code before it being used.
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or
declare the exception.
In this section, we will learn how custom exceptions are implemented and used in
Java programs.
In order to create custom exception, we need to extend Exception class that belongs
to java.lang package.
Note: We need to write the constructor that takes the String as the error message and it
is called parent class constructor.
Example 1:
Let's see a simple example of Java custom exception. In the following code,
constructor of InvalidAgeException takes a string as an argument. This string is
passed to constructor of parent class Exception using the super() method. Also the
constructor of Exception class can be called without using a parameter and calling
super() method is not mandatory.
TestCustomException1.java
Output: