Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.
In this page, we will learn about Java exceptions, its type and the difference between checked and unchecked
exceptions.
What is Exception in Java
Dictionary Meaning: Exception is an abnormal condition.In Java, an exception is an event that disrupts the
normal flow of the program. It is an object which is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the
unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked
exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Keyword Description
try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
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 important code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with method
signature.
Java Exception Handling Example
Let's see an example of Java Exception Handling where we using a try-catch statement to handle the
exception
public class JavaExceptionExample
{
public static void main(String args[])
{
Try
{
int data=100/0;
}
catch(ArithmeticException e){System.out.println(e);
}
System.out.println("rest of the code...");
}
}
Compile by: javac JavaExceptionExample.java
Run by: java JavaExceptionExample
java.lang.ArithmeticException: / by zero
rest of the code...
b. Handling Exceptions using try, catch, throws, finally
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So,
it is recommended not to keeping the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
Try
{
//code that may throw an exception
}
catch(Exception_class_Name ref){}
Syntax of try-finally block
Try
{
//code that may throw an exception
}
finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The
declared exception must be the parent class exception ( i.e., Exception) or the generated exception type.
However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a single try
block.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
Example 1
public class TryCatchExample1
{
public static void main(String[] args)
int data=50/0; //may throw exception
System.out.println("rest of the code");
As displayed in the above example, the rest of the code is not executed (in such case, the rest of the
code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Solution by exception handling
Let's see the solution of the above problem by a java try-catch block.
Example 2
public class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
Now, as displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.
Example 3
In this example, we also kept the code in a try block that will not throw an exception.
public class TryCatchExample3
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
Java throw exception
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly
used to throw custom exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.
throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error);
java throw keyword example
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.
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Difference between final, finally and finalize
There are many differences between final, finally and finalize. A list of differences between final, finally and
finalize are given below
No. final finally finalize
1) Final is used to apply restrictions Finally is used to place Finalize is used to
on class, method and variable. important code, it will perform clean up
Final class can't be inherited, final be executed whether processing just before
method can't be overridden and exception is handled object is garbage
final variable value can't be or not. collected.
changed.
2) Final is a keyword. Finally is a block. Finalize is a method.
Java final example
Class FinalExample
{
public static void main(String[] args)
{
final int x=100;
x=200;//Compile Time Error
}}
Java finally example
class FinallyExample
{
public static void main(String[] args)
{
Try
{
int x=300;
}catch(Exception e){System.out.println(e);
}
finally{System.out.println("finally block is executed");
}
}
Java finalize example
class FinalizeExample{
public void finalize(){System.out.println("finalize called");
}
public static void main(String[] args)
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}