In this java exception handling tutorial, we will learn, what is an exception, how to handle exceptions, and important keywords and classes of exception handling in java with an example.
What is an Exception
An exception is an abnormal condition, which occurs at run time and terminates the flow of the program.
Just think about a situation where you have created a java program for division. In that example you have two numbers, the first number will be divided by the second number. But at the run time user will divide the first number by zero. As we know that division by zero is not possible, so it will generate an exception.
Java example to generate an exception.
class Demo
{
public static void main(String args[])
{
int n=10;
System.out.println(n/0);
//above line will generate an exception
}
}
Why is an Exception generated?
An exception can be generated for many reasons, some of which are:
- When the user input invalid (wrong type) data.
- When we try to divide a number by zero.
- If we want to open a file through code, which does not exist.
- When we want to access an array index that does not exist.
How to Handle an Exception.
Handling an exception is very important because we can give a proper useful message to the user when an exception occurs. Java has many classes and keywords to manage exceptions.
Java Exception Handling Keywords.
Java has some keywords to manage and generate an exception.
- try – It is a block in java, which includes the code which may generate an exception.
- catch – It is used with the try block and executes only when an exception generates.
- finally – It is also used with try and always executes whether an exception is generated or not.
- throw – It is used to generate an exception forcefully.
- throws – It indicates what type of exception may be thrown by a method.
Java Exception Handling Classes
In Java, exceptions are generated as an object of the exception class. All the classes are subclasses of the Exception class and Exception is a subclass of the Throwable class. Some important exception classes are listed below.
- ArithmeticException – This type of exception is thrown when an exceptional mathematical condition occurs.
- FileNotFoundException – It threw when a code fails to open a file.
- ArrayIndexOutOfBoundsException – It threw when a code tries to access an array element with an illegal index.
- NumberFormatException – It threw when we try to convert an appropriate format of a string to a number type.
- IOException – It generates when a code fails to read or write a file.
- SQLException – SQLException occurs when code is unable to communicate with the database.
Handle an Exception in Java using try and catch.
Here, we are discussing an example program that accepts numbers and prints the division of given numbers. In this example Whenever we try to divide a number by zero, the given code will generate an exception of ArithmeticException.
Java program which may generate an exception.
import java.util.*;
class Demo
{
public static void main(String args[])
{
int x,y,z;
Scanner in=new Scanner(System.in);
//accepting input from user
System.out.println("Enter First Number");
x=in.nextInt();
System.out.println("Enter Second Number");
y=in.nextInt();
//calculate and print division of numbers
z=x/y;
System.out.println(z);
//above line will generate an exception, if we divide a number by zero.
}
}
The above code will generate an exception if we try to divide a number by zero. In the below program, we will learn to manage this situation and print a proper message to the user.
Java program to handle an exception using try and catch block.
import java.util.*;
class Demo
{
public static void main(String args[])
{
int x,y,z;
Scanner in=new Scanner(System.in);
//starting a try block, it includes code that may generate an exception
try
{
//accepting input from user
System.out.println("Enter First Number");
x=in.nextInt();
System.out.println("Enter Second Number");
y=in.nextInt();
//calculate and print division of numbers
z=x/y;
System.out.println(z);
//above line will generate an exception, if we divide a number by zero.
}
catch(ArithmeticException e)
{
System.out.println("Division by zero is not possible");
}
//catch must be after a try block to catch the exception.
}
}
Always write the code which may generate an exception within a try block, whenever an exception is generated it throws it. When a try block throws the exception then the catch block catch that exception and prints a proper message.
Multiple catch blocks can be possible with a try block.
In Java, multiple catch blocks are possible with a try block to handle different types of exceptions.
import java.util.*;
class Demo
{
public static void main(String args[])
{
int x,y,z;
Scanner in=new Scanner(System.in);
//starting a try block, it includes code that may generate an exception
try
{
//accepting input from user
System.out.println("Enter First Number");
x=in.nextInt();
System.out.println("Enter Second Number");
y=in.nextInt();
//calculate and print division of numbers
z=x/y;
System.out.println(z);
//above line will generate an exception, if we divide a number by zero.
}
catch(ArithmeticException e1)
{
System.out.println("Division by zero is not possible");
}
catch(InputMismatchException e2)
{
System.out.println("Please enter number only");
}
catch(Exception e3)
{
System.out.println("Some error: "+e3);
}
}
}
In the above program, we have multiple catch blocks with different arguments to handle different types of exceptions. Only one catch block will execute based on the type of exception generated.
The finally block in Java.
The finally block is always executed whether an exception is generated or not. So, all the important code that must be executed should be within the finally block.
import java.util.*;
class Demo
{
public static void main(String args[])
{
int x,y,z;
Scanner in=new Scanner(System.in);
//starting a try block, it includes code that may generate an exception
try
{
//accepting input from user
System.out.println("Enter First Number");
x=in.nextInt();
System.out.println("Enter Second Number");
y=in.nextInt();
//calculate and print division of numbers
z=x/y;
System.out.println(z);
//above line will generate an exception, if we divide a number by zero.
}
catch(ArithmeticException e1)
{
System.out.println("Division by zero is not possible");
}
catch(InputMismatchException e2)
{
System.out.println("Please enter number only");
}
catch(Exception e3)
{
System.out.println("Some error: "+e3);
}
finally
{
System.out.println("Always Print");
}
}
}
throw and throws keywords in Java.
If we want to generate an exception for a reason, we use the throw keyword. We use throws with the method declaration to indicate the type of exception to be generated.
import java.util.*;
class Demo
{
public static void votingAge(int age) throws Exception
{
if(age<18)
throw new Exception("You are not eligible for vote");
else
System.out.println("You are eligible for vote");
}
public static void main(String args[])
{
int age;
Scanner in=new Scanner(System.in);
try
{
System.out.println("Enter Your Age");
age=in.nextInt();
votingAge(age);
}
catch(Exception e)
{
System.out.println("Some error: "+e);
}
}
}
As we know throw keyword in java is used to throw an exception forcefully. In the above example, we have a method to test the voting age of a person. We want to generate an exception if the age is less than 18. To generate an exception explicitly we use the throw keyword and we used the throws keyword in the method declaration to indicate which type of exception might occur.
Note: In the above example votingAge() method is a static, that’s why we call it without object reference in the main() method. A static method can call directly in another static method.