What is Exception Handling in Java?
Exception handling in java helps in minimizing exceptions and helps in recovering from
exceptions. It is one of the powerful mechanisms to handle runtime exceptions and makes it
bug-free.
Exception handling helps in maintaining the flow of the program. An exception handling is
defined as an abnormal condition that may happen at runtime and disturb the normal flow of
the program.
Learn Java Programming
What is an Exception?
An expectation is an unexpected event that occurs while executing the program, that disturbs
the normal flow of the code.
Exception handling in java with an example:
Let’s say,
statement
statement
statement
exception ………… an exception occurred, then JVM will handle it and will exit the prog.
statement
statement
statement
For handling exceptions, there are 2 possible approaches
1. JVM
If an exception is not handled explicitly, then JVM takes the responsibility of handling the
exception.
Once the exception is handled, JVM will halt the program and no more execution of code
will take place
Example:
import [Link].*;
class Main {
public static void main (String[] args) {
[Link](5/0);
[Link]("End of program!");
}
}
Runtime Error:
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
2. Developer
Developers can explicitly write the implementation for handling the exception. Once an
exception is handled, the normal execution of code will continue.
Preferable: handle exceptions to ensure your code gets executed normally.
Java Exception Hierarchy
Exception Hierarchy – Following is the Exception Handling in Java handling hierarchy.
Throwable –
It is the root class for the exception hierarchy in java.
It is in the [Link] package.
Error –
Subclass of Throwable.
Consist of abnormal condition that is out of one’s control and depends on the
environment
They can’t be handled and will always result in the halting of the program.
Eg: StackOverFlowError that can happen in infinite loop or recursion
Exception –
Subclass of Throwable.
Consist of abnormal conditions that can be handled explicitly.
If one handles the exception then our code will continue to execute smoothly.
Types of exception in Java
Checked Exceptions
Those exceptions that are checked at compile-time comprises checked
exceptions.
They are child classes of Exception except for RuntimeException.
The program will not compile if they are not handled.
Example: IOException, ClassNotFoundException, etc.
Unchecked Exceptions
Those exceptions that are checked at runtime comprises unchecked
exceptions.
They are child classes of RuntimeException.
They give runtime errors if not handled explicitly.
Example: ArithmeticException, NullPointerException etc.
Difference between Checked and Unchecked Exception
Checked Exceptions Unchecked Exceptions
Occur at compile time. Occur at runtime.
The compiler checks for a checked
The compiler doesn’t check for exceptions.
exception.
Can’t be caught or handled during
Can be handled at the compilation time.
compilation time.
The JVM requires that the exception be The JVM doesn’t require the exception to
caught and handled. be caught and handled.
Example of Checked exception- ‘File Example of Unchecked Exceptions- ‘No
Not Found Exception’ Such Element Exception’
Java Exception Index
Java Exception Keywords
Exception Handling in java is managed via five keywords: try, catch, throw, throws, and finally. Here
are 5 keywords that are used in handling exceptions in Java
Keyword Description
This keyword is used to specify a block and this block must be followed
try
by either catch or finally. That is, we can’t use try block alone.
This keyword must be preceded by a try block to handle the exception and
catch
can be followed by a final block later.
This keyword is used to execute the program, whether an exception is
finally
handled or not.
throw This keyword is used to throw an exception.
throws This keyword is used to declare exceptions.
Java Try-Catch Block
Try-catch syntax:
try{
}
catch(Exception e){
}
Try-catch Example:
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
[Link](a/i);
}catch(ArithmeticException e){
[Link](e);
}
}
}
Output:
3
5
10
[Link]: / by zero
try block contains the code that might throw an exception. Don’t write anything extra
in try as statements after the exception will not get executed if the exception occurred.
Try must be immediately followed by catch or finally block.
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
[Link](a/i);
}
}
}
Compile-time error:
[Link][Link] error: 'try' without 'catch', 'finally' or resource declarations
try{
^
1 error
The catch block is used to catch the exception thrown by statements in the try block.
The catch must follow try else it will give a compile-time error.
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
[Link](a/i);
}
[Link]("between try and catch");
catch(ArithmeticException e){
[Link](e);
}
}
}
Compile Time Error:
[Link][Link] error: 'try' without 'catch', 'finally' or resource declarations
try{
^
[Link][Link] error: 'catch' without 'try'
catch(ArithmeticException e){
^
2 errors
Things to Remember:
Do not keep any code after the statement which is prone to exception. Because if an
exception occurred, it will straight away jump to the catch or finally block, ignoring all other
statements in the try block.
class Main {
public static void main (String[] args) {
try
{
[Link](4/0);
//will not get printed
[Link]("end of try!");
}
catch(ArithmeticException e)
{
[Link]("divide by 0");
}
}
}
Output:
divide by 0
While catching the exception in the catch block, either you can have directly the class
of exception or its superclass.
Example: Exact Exception
class Main {
public static void main (String[] args) {
try{
[Link](4/0);
}
//ArithmeticException
catch(ArithmeticException e){
[Link]("divide by 0");
}
}
}
Output:
divide by 0
Example: Superclass of Exact Exception
class Main {
public static void main (String[] args) {
try{
[Link](4/0);
}
//superclass of ArithmeticException
catch(Exception e){
[Link]("divide by 0");
}
}
}
Output:
divide by 0
Java Multiple Catch Block
If you have multiple catches, you have to maintain the hierarchy from subclass to superclass.
Incorrect:
class Main {
public static void main (String[] args) {
try{
[Link](4/0);
}catch(Exception e)
{
[Link]("Exception : divide by 0");
}catch(ArithmeticException e)
{
[Link]("ArithmeticException :divide by 0");
}
}
}
Compile-time error:
[Link][Link] error: exception ArithmeticException has already been caught
}catch(ArithmeticException e)
^
1 error
Correct:
class Main {
public static void main (String[] args) {
try{
[Link](4/0);
}catch(ArithmeticException e)
{
[Link]("ArithmeticException : divide by 0");
}catch(Exception e)
{
[Link]("Exception : divide by 0");
}
}
}
Output:
ArithmeticException: Divide by 0
Java Nested Try
When there is another try block within the try block:
class Main {
public static void main (String[] args) {
try{
try{
int[] a={1,2,3};
[Link](a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Out of bounds");
}
[Link](4/0);
}
catch(ArithmeticException e)
{
[Link]("ArithmeticException : divide by 0");
}
}
}
Output:
Out of bounds
ArithmeticException: Divide by 0
Note – If we put code of outer try before inner try, then if an exception occurred, it will
ignore the entire inner try and move directly to its catch block.
class Main {
public static void main (String[] args) {
try{
[Link](4/0);
try{
int[] a={1,2,3};
[Link](a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Out of bounds");
}
}
catch(ArithmeticException e)
{
[Link]("ArithmeticException : divide by 0");
}
}
}
Output:
ArithmeticException: Divide by 0
Java Finally Block
Contains code that must be executed no matter if an exception is thrown or not. It contains
code of file release, closing connections, etc.
Example:
class Main {
public static void main (String[] args) {
try{
[Link](4/0);
}catch(Exception e)
{
[Link](e);
}
finally
{
[Link]("finally executed");
}
[Link]("end");
}
}
Output:
[Link]: / by zero
finally executed
end
Finally, will execute even when we do not handle exceptions. Before halting the program,
JVM checks if there is a “finally” block.
class Main {
public static void main (String[] args) {
try{
[Link](4/0);
}finally
{
[Link]("cleaning.......");
}
}
}
Runtime Error:
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
Output:
cleaning.......
Java Final vs Finally vs Finalize
Final Finally Finalize
Final is used to apply Finally is used in coding, it Finalize is used to perform
restrictions on class, will be executed whether an clean-up processing before
method, and variable exception is handled or not. garbage is collected.
Final is a keyword in
Finally is a block in java Finalize is a method in java
java
finalize executes just before
Final is executed upon Finally executes after”try-
the destruction of the
its call. catch” block.
object.
Java Throw Keyword
It is a keyword that is used to explicitly throw an exception.
We can use throw where according to our logic an exception should occur.
Example:
public class ExceptionDemo {
static void canVote(int age){
if(age<18)
try{
throw new Exception();
}catch(Exception e){
[Link]("you are not an adult!");
}
else
[Link]("you can vote!");
}
public static void main (String[] args) {
canVote(20);
canVote(10);
}
}
Output:
you can vote!
you are not an adult!
Java Throws Keyword
Throws keyword is used when callee doesn’t want to handle the exception rather it
wants to extend this responsibility of handling the exception to the caller of the
function.
Basically says what sort of exception the code can throw and relies on the caller to
handle it.
It is used to handle checked Exceptions as the compiler will not allow code to compile
until they are handled.
Example:
public class ExceptionDemo {
static void func(int a) throws Exception{
[Link](10/a);
}
public static void main (String[] args) {
try{
func(10);
func(0);
}catch(Exception e){
[Link]("can't divide by zero");
}
}
}
Output:
1
can't divide by zero
If callee can throw multiple exceptions, then all will be thrown simultaneously.
import [Link].*;
public class ExceptionDemo {
static void func(int a,int b) throws ArithmeticException,
ArrayIndexOutOfBoundsException{
[Link](10/a);
int[] arr={1,2,3};
[Link](arr[b]);
}
public static void main (String[] args) {
Scanner in=new Scanner([Link]);
for(int i=0;i<3;i++){
try{
func([Link](),[Link]());
}catch(ArithmeticException e){
[Link]("can't divide by zero");
}catch(ArrayIndexOutOfBoundsException e){
[Link]("Out of bounds!");
}
}
}
}
Input:
21
01
23
Output:
5
2
can't divide by zero
5
Out of bounds!
Java Throw vs Throws
Throw Throws
This keyword is used to explicitly throw This keyword is used to declare an
an exception. exception.
A checked exception cannot be A checked exception can be propagated
propagated with throw only. with throws.
The throw is followed by an instance Throws are followed by class and used
and used with a method with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions
Java Custom Exception
You can create your own exception and give implementation as to how it should behave.
Your exception will behave like a child’s class of Exception.
Syntax:
1 class YourException extends Exception{}
Example:
let’s say, you are working with an airline company
You are in the luggage check-in department and as per rules, you can allow
15kg per customer.
So now more than 15kg of weight is an abnormal condition for us or in other
words its an exception
This is our logic-based exception, so we’ll create our custom exception
WeightLimitExceeded
As per syntax, it will extend Exception.
We define the constructor which will get invoked as soon as an exception will
be thrown
We have to explicitly throw the exception and hence we will use throw
keyword for that.
Using throws keyword is as per our need. If we are handling an exception
where it is getting thrown then we can avoid throws, else we will use throws and
handle it in the caller.
Implementation:
import [Link].*;
class WeightLimitExceeded extends Exception{
WeightLimitExceeded(int x){
[Link]([Link](15-x)+" kg : ");
}
}
class Main {
void validWeight(int weight) throws WeightLimitExceeded{
if(weight>15)
throw new WeightLimitExceeded(weight);
else
[Link]("You are ready to fly!");
}
public static void main (String[] args) {
Main ob=new Main();
Scanner in=new Scanner([Link]);
for(int i=0;i<2;i++){
try{
[Link]([Link]());
}catch(WeightLimitExceeded e){
[Link](e);
}
}
}
}
Input:
20
7
Output:
5 kg : WeightLimitExceeded
You are ready to fly!
Java Exception Handling
In the last tutorial, we learned about Java exceptions. We know that exceptions abnormally
terminate the execution of a program.
This is why it is important to handle exceptions. Here's a list of different approaches to
handle exceptions in Java.
try...catch block
finally block
throw and throws keyword
1. Java try...catch block
The try-catch block is used to handle exceptions in Java. Here's the syntax
of try...catch block:
try {
// code
}
catch(Exception e) {
// code
}
Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by a catch block.
When an exception occurs, it is caught by the catch block. The catch block cannot be used
without the try block.
Example: Exception handling using try...catch
class Main {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
[Link]("Rest of code in try block");
}
catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}
}
}
Run Code
Output
ArithmeticException => / by zero
In the example, we are trying to divide a number by 0 . Here, this code generates an
exception.
To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an
exception occurs, the rest of the code inside the try block is skipped.
The catch block catches the exception and statements inside the catch block is executed.
If none of the statements in the try block generates an exception, the catch block is
skipped.
2. Java finally block
In Java, the finally block is always executed no matter whether there is an exception or
not.
The finally block is optional. And, for each try block, there can be only one finally block.
The basic syntax of finally block is:
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
If an exception occurs, the finally block is executed after the try...catch block. Otherwise,
it is executed after the try block. For each try block, there can be only one finally block.
Example: Java Exception Handling using finally block
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}
finally {
[Link]("This is the finally block");
}
}
}
Run Code
Output
ArithmeticException => / by zero
This is the finally block
In the above example, we are dividing a number by 0 inside the try block. Here, this code
generates an ArithmeticException .
The exception is caught by the catch block. And, then the finally block is executed.
Note: It is a good practice to use the finally block. It is because it can include important
cleanup codes like,
code that might be accidentally skipped by return, continue or break
closing a file or connection
3. Java throw and throws keyword
The Java throw keyword is used to explicitly throw a single exception.
When we throw an exception, the flow of the program moves from the try block to
the catch block.
Example: Exception handling using Java throw
class Main {
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}
Run Code
Output
Exception in thread "main" [Link]: Trying to divide by 0
at [Link]([Link])
at [Link]([Link])
In the above example, we are explicitly throwing the ArithmeticException using
the throw keyword.
Similarly, the throws keyword is used to declare the type of exceptions that might occur
within the method. It is used in the method declaration.
Example: Java throws keyword
import [Link].*;
class Main {
// declareing the type of exception
public static void findFile() throws IOException {
// code that may generate IOException
File newFile = new File("[Link]");
FileInputStream stream = new FileInputStream(newFile);
}
public static void main(String[] args) {
try {
findFile();
}
catch (IOException e) {
[Link](e);
}
}
}
Run Code
Output
[Link]: [Link] (The system cannot find the file specified)
When we run this program, if the file [Link] does not exist, FileInputStream throws
a FileNotFoundException which extends the IOException class.
The findFile() method specifies that an IOException can be thrown. The main() method
calls this method and handles the exception if it is thrown.
If a method does not handle exceptions, the type of exceptions that may occur within it must
be specified in the throws clause.