Exception Handling in Java
Exception Handling in Java
In this lesson, we will learn about exceptions and how to handle them in java.
What is Exception in Java?
An exception is a condition that arises due to an error that occurs during the runtime of a program.
What is Exception Handling in Java?
Exception handling is a procedure in Java in which runtime errors that may occur when a program is being executed are handled properly so the program can continue its execution without unexpectedly ending due to a runtime error.
Types of Exception in Java
There are two types of exception in Java and they are:
- Checked Exceptions
- Unchecked Exceptions
Checked Exceptions
Checked exceptions are those that the compiler verifies at the time of compilation. A method must handle any checked exceptions it throws or explicitly states the exception using the throws keyword. IOException, SQLException, and ClassNotFoundException are a few examples of checked exceptions.
Unchecked Exceptions
Unchecked exceptions are those that the compiler does not verify at the time of compilation, but these exceptions occur at runtime. They are also known as runtime exceptions.
These exceptions arise due to an error in the program, like null pointer exceptions, index out of bounds exceptions, and arithmetic exceptions. NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException are a few examples of unchecked exceptions.
List of Common Exceptions in Java
EXCEPTION TYPE | CAUSE OF EXCEPTION |
ArithmeticException | Occur when a number is divided by zero. |
ArrayIndexOutOfBoundsException | Occur when try to access an index that does not exist in an array. |
StringIndexOutOfBoundsException | Occur when try to access an index that does not exist in a string. |
NumberFormatException | Occur when a conversion between string and number fails. |
InputMismatchException | Occur when an invalid input is given to store in a variable. |
ClassNotFoundException | Occur when unable to find a specified class. |
FileNotFoundException | Occur when unable to find a specified file. |
IOException | Occur due to input/output failures. |
OutOfMemoryException | Occur when there is not enough memory to allocate a new object. |
NullPointerException | Occur when trying to use a null object reference. |
SecurityException | Occur when a security violation occurs. |
How to Handle Exceptions in Java
We can handle exceptions in Java using the try-catch statement. Let's raise an ArithmeticException and handle it with the try-catch statement.
Example
public class Example
{
public static void main(String args[])
{
int a=5,b=0,c;
c=a/b;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("Result="+c);
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero at Example.main(Example.java:7)
In the above program, when we try to divide the number 5 by 0, the program raises an ArithmeticException on line number 7, and the program terminates without executing the rest of the lines after line 7.
Now we will handle the ArithmeticException raised on line 7 using the try-catch statement so that the program does not terminate whenever the exception occurs. Let's see the syntax of try-catch statement.
try-catch Statement Syntax
try
{
// statements that may raise an exception
}
catch(exception_type object_name)
{
// manage the exception as per your requirements
}
Example
public class Example
{
public static void main(String args[])
{
int a=5,b=0,c=0;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("Can't divide number by 0");
}
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("Result="+c);
}
}
Output
Can't divide number by 0 a=5 b=0 Result=0
In the above program, the variable e in the catch statement represents an object of the thrown exception. This object contains details about the thrown exception, including the error message, the stack trace, etc.
The catch statement can use this information to manage the exception by presenting an error message to the user or logging the exception details in an error log file for further investigation.
To get the error message from the object of the thrown exception, we need to use the getMessage() method of the object. See the example given below.
Example
public class Example
{
public static void main(String args[])
{
int a=5,b=0,c=0;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("Result="+c);
}
}
Output
/ by zero a=5 b=0 Result=0
Multiple catch Statements
We can handle multiple exceptions in a catch block using multiple catch statements by specifying each exception type in an individual catch statement.
Example
import java.util.*;
public class Example
{
public static void main(String args[])
{
int a=0,b=0,c=0,i=0;
String str;
Scanner sc=new Scanner(System.in);
try
{
System.out.println("Enter 2 integer numbers");
a=sc.nextInt();
b=sc.nextInt();
c=a/b;
sc.nextLine();
System.out.println("Enter a string");
str=sc.nextLine();
System.out.println("Enter an index to print the character from the above given string");
i=sc.nextInt();
System.out.println(str.charAt(i));
}
catch(ArithmeticException e)
{
System.out.println("Can't divide by 0.");
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please enter an integer number.");
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("Index does not exist.");
}
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("Result="+c);
}
}
Output 1
Enter 2 integer numbers 5.2 Invalid input. Please enter an integer number. a=0 b=0 Result=0
Output 2
Enter 2 integer numbers 5 0 Can't divide by 0. a=5 b=0 Result=0
Output 3
Enter 2 integer numbers 5 2 Enter a string Dremendo Enter an index to print the character from the above given string 15 Index does not exist. a=5 b=2 Result=2
Using finally Statement
The finally statement is an optional statement in a try-catch block. Whether an exception is thrown or not, when a finally block is defined, this is guaranteed to run. We can use it to conduct operations like closing a file or freeing up system resources.
Example
try
{
// statements that may raise an exception
}
catch(exception_type object)
{
// manage the exception as per your requirements
}
finally
{
// statements that need to be executed after the try block ends
}