Exception Handling in Java | Types of Exceptions in Java With Example Programs

Exception Handling in Java is one of the most powerful features that allow us to handle the runtime error so that the normal flow of the program can be maintained. In this tutorial, we will learn What is an exception, Types of exception, exception classes, how to handle the exception in Java, and the difference between error and exception. Before discussing exception handling in java in detail let’s first understand What is an exception.

This Java Exception Handling tutorial contains the following

What is Exception in Java?

Exceptions in Java are any abnormal, unwanted events, or extraordinary conditions that may occur at runtime. It interrupts the normal flow of the program. Exception terminated the program execution. When an exception occurs we get a system-generated error message. The good news is that exceptions can be handled in Java. Therefore we can provide a meaningful message to the user rather than the system generated an error message, which not understandable to a user.

Why an exception occurs?

Exceptions in Java can occur due to the following reasons:

  • Wrong data entered by the user.
  • Network Connection problem.
  • Hardware problem.
  • Opening a file which is not existing in your program.
  • Server down problem.

What is Exception Handling?

Exception Handling in Java is a powerful mechanism that is used to handle runtime errors, compile-time errors are not handled by exception handling in Java. If an exception occurs in your code (suppose in line 6), then the rest of the code is not executed. Therefore Java compiler creates an exception object and this exception object directly jumps to the default catch mechanism. Where there is a default message which is print on the screen and our program gets terminated.

Also See:

Advantages of Exception Handling in Java

It maintains the normal flow of the program. Suppose in your program there are many statements and an exception occurs midway then the statements after the exception will not execute and the program will terminate and we get system generated error message. Which are not understandable to a user.

By exception handling mechanism all the statements in your program will execute and do not break the normal flow of the program and it generated a user-friendly message rather than the system generated an error message.

Difference between Exception and Errors

Errors: Most of the time errors are not caused by our programs these are due to a lack of system resources. Errors are not recoverable (not handle).

For example, if an OutOfMemory error occurs during the execution of a program we can’t do anything and the program will be terminated abnormally.

Exceptions: Exceptions in Java are any abnormal, unwanted events, or extraordinary conditions that may occur at runtime. Exceptions are caused by our program and exceptions are recoverable.

Few instances of exceptions: ArithmaticException, NullPointerException, ClassNotFoundException, IOException, etc.

Hierarchy of Java Exception Classes

  • Throwable is the parent class of all exception classes in java.
  • Throwable has two child classes: Error and Exception.
  • The Exception class represents the exception that can be handled by our program using try and catch block.
  • RuntimeException is a child class of exception class. These types of exceptions may occur at runtime. ArithmeticException, NullPointerException, etc. are the example of runtime exception.

Exception Handling in Java - Types of Exceptions in Java

Java Exception Keywords

There are 5 keywords that are used for exception handling in Java:

1. try: In the java, try block we can write the code that might throw an exception. A try block in Java must be followed by either at least one catch block or one finally block.

2. catch: catch block in Java is used to handle the exception that may occur in our program. It must be used after try block only. We can use more than one catch block with a single try block.

3. finally: finally block in Java can be used to clean up code or release some resources that are utilized in the program. finally block is always run whether the exception handled or not.

4. throw: throw keyword in java can be used to throw an exception. It can throw exceptions explicitly. We can throw either checked or unchecked exceptions using the throw keyword.

Syntax:

throw an exception;

5. throws: throws keyword in java is used for declaring an exception. We can declare only checked exceptions using the throws keyword. So it’s the programmer’s responsibility to provide the exception handling code so that the normal flow of the program can be maintained.

Syntax:

return_type method_name() throws exception_class_name.

Exceptions Methods

From the below table, you will see the list of important methods obtained in the Throwable class:

Method Description
public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
public Throwable getCause() Returns the cause of the exception as represented by a Throwable object.
public String toString() Returns the name of the class concatenated with the result of getMessage().
public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream.
public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Java Exception Handling Example

Let’s take a look at the sample program on Java Exception Handling by using a try-catch statement to handle the exception:

public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Types of Exceptions in Java

There are two types of Exception in Java:

  1. Checked Exception
  2. Unchecked Exception

1. Checked Exceptions

All the classes which inherit the throwable class except RuntimeException and Error are known as Checked Exception. The checked exceptions are checked by the compiler at compile-time. In case of checked exceptions if programmers will not handle the exception then we will get a compile-time error. We will handle the checked exception by using a try-catch block or and declare using the throws keyword. For example, FileNotFoundException, ClassNotFoundException, IOException, SQLException etc.

Checked Exception Example:

In this example, we are reading the file abc.txt and displaying its content on the screen. Here we are using FileInputStream for reading the data from a file, it throws FileNotFoundException. The read() method which is used for reading the data from the input stream and the close() method which is used for closes the file input stream throws an IOException.

import java.io.*;
class ExceptionExample{
public static void main(String args[]){

FileInputStream fis = null;

//FileInputStream throws
//FileNotFoundException which is
// a checked exception.
fis = new FileInputStream("D:/abc.txt");
int i;

//read() method of FileInputStream
//class also throws an IOException.
while(( i = fis.read() ) != -1 ){
System.out.println((char)i);
}

//close() method used for
//close the file input stream
//it throws an IOException.
fis.close();
}
}

Output:

error: unreported exception FileNotFoundException
fis = new FileInputStream("D:/abc.txt");
error: unreported exception IOException
while(( i = fis.read() ) != -1 ){
error: unreported exception IOException
fis.close();

There are two ways to handle this error:

  1. Using try-catch.
  2. Using throws keyword.

Java try…catch block

The try-catch block is used to handle exceptions in Java. Below, we have given the syntax of try…catch block:

try {
// code
}
catch(Exception e) {
// code
}

In the above syntax, we have placed the code that might generate an exception inside the try block. Every try block is followed by a catch block.

Handle Checked Exception using a try-catch block

It is a good practice to handle the exception using a try-catch block Because you should give a meaningful message for each exception type so that it would be easy for someone to understand the error.

import java.io.*;
class ExceptionExample{
public static void main(String args[]){
FileInputStream fis = null;
try{
fis = new FileInputStream("D:/abc.txt");
}
catch(FileNotFoundException fn){
System.out.println("The file is not present at given path");
}
int i;
try{
while(( i = fis.read() ) != -1 ){
System.out.println((char) i);
}
fis.close();
}
catch(IOException ie){
System.out.println("IOException occured: " +ie);
}
}
}

Java throw and throws keyword

The throw keyword in java is utilized to explicitly throw a single exception.

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();
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)

Declare the exception using the throws keyword

As we know that checked exception occurs inside the main() method. So you can declare the exception in the main() method using the throws keyword. You can declare the exception like this:

public static void main(String args[]) throws IOException;

IOException is the parent class of FileNotFoundException so that it by default handle the FileNotFoundException.

import java.io.*;
class ExceptionExample{

//handled exception using throws keyword.
public static void main(String args[]) throws IOException{
FileInputStream fis = null;
fis = new FileInputStream("D:/abc.txt");
int i;
while(( i = fis.read() ) != -1 ){
System.out.println((char) i);
}
fis.close();
}
}

All the above two programs are work fine and display file content.

Java finally block

In Java, the finally block is always performed no matter whether there is an exception or not. The finally block is optional. Moreover, for each try block, there can be only one finally block.

The basic syntax of finally block is as follows;

try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}

2. Unchecked Exceptions

All the classes which inherit RuntimeException are known as Unchecked Exception. The Unchecked exceptions are not checked by the compiler at compile-time. But they are checked at runtime. In the case of an Unchecked exception if programmers will not handle the exception then we won’t get a compile-time error. Most of the time these exceptions occur due to the wrong data entered by the user (divide by zero). In such types of exceptions, the compiler will never force you to handle the exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBounds etc.

Example of Unchecked Exception:

In this example, we are dividing two numbers that are entered by the user. If the user enters the right data then our program will display a division of two numbers. If the user enters the wrong data then our program will display ArithmeticException. These exceptions will not occur at compile-time, it can occur at runtime.

import java.util.*;
class ExceptionExample{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);

//enter first number by user.
System.out.println("Enter the first number: ");
int num1 = sc.nextInt();

//enter second number by user.
System.out.println("Enter the second number: ");
int num2 = sc.nextInt();

//calculate result.
int result = num1/num2;
System.out.println("Division of two number is: " +result);
System.out.println("Program continues!");
}
}

Output: When a user enters the right data.

Enter the first number: 20
Enter the second number: 10
The division of two number is: 2
Program continues!

Output: When a user enters the wrong data.

Enter the first number: 20
Enter the second number: 0
error: exception in thread "main" java.lang.ArithmeticException: / by zero

Let’s see another example in this example we are taking an example of an array. Here my array has only 5 elements but we are trying to display the value of the 10th element. It should throw an exception ArrayIndexOutOfBoundsException.

class UncheckedException{
public static void main(String args[]){

/* This array has only 5 elements but
we are trying to display the value of the 10th element.
It should throw ArrayIndexOutOfBoundsException.
*/
int arr[] = {1,2,3,4,5};
System.out.println("The value of 10th element is:" +arr[10]);
}
}

Unchecked Exception handled using try and catch block:

class UncheckedException{
public static void main(String args[]){
try{
System.out.println(12/0);
System.out.println("We are in try block");
}
catch(ArithmeticException e){
System.out.println("Exception: " +e.getMessage());
}
System.out.println("Programs continues!");
}
}

Output:

Exception: / by zero.
Program continues!

Difference between Checked and Unchecked Exceptions

All the classes which inherit throwable class except RuntimeException and Error are known as Checked Exception while all the classes which inherit RuntimeException are known as Unchecked Exception.

The checked exceptions are checked by the compiler at compile-time while the Unchecked exceptions are not checked by the compiler at compile-time. But they are checked at runtime.

In case of checked exception, if programmers will not handle the exception then we will get a compile-time error while in case of Unchecked exception if programmers will not handle the exception then we won’t get a compile-time error.

FileNotFoundException, ClassNotFoundException, IOException, SQLException, etc. are the example of checked exception while ArithmeticException, NullPointerException, ArrayIndexOutOfBounds, etc. are the example of Unchecked exception.

Multiple Catch Blocks

If we want to perform a different task at the occurrence of different exceptions then we should go for multiple catch blocks. Let’s see an example of multiple catch blocks in Java.

class UncheckedException{
public static void main(String args[]){
try{
int arr[] = new int[5];
arr[3] = 12/0;
System.out.println("We are in try block");
}
catch(ArithmeticException ae){
System.out.println("Divide by zero exception");
}
catch(ArrayIndexOutOfBoundsException ae){
System.out.println("array elements outside limit");
}
catch(Exception e){
System.out.println("Other type of exception");
}
System.out.println("We are outside the try catch block");
}
}

Output:

Divide by zero exception
We are outside the try-catch block

Explicitly throw an Exception in Java

throw keyword in Java can be used to throw an exception. It can throw exceptions explicitly. We can throw either checked or unchecked exceptions using the throw keyword. Let’s understand with a simple example. In this example, we have created a two-variable balance and withdrawal amount. If the balance is less than the withdrawal amount then ArithmeticException has occurred. Therefore we throw an object of ArithmeticException and it will display a message on the screen “insufficient balance”.

class ExceptionExample{
public static void main(String args[]){
int balance = 5000;
int withdrawlAmount = 6000;

try{
if(balance < withdrawlAmount)
throw new ArithmeticException("Insufficient balance");
balance = balance-withdrawlAmount;
System.out.println(" Transactions successfully completed");
}
catch(ArithmeticException e){
System.out.println("Exception is: " +e.getMessage());
}
System.out.println("Programs continues!");
}
}

Output:

The exception is: Insufficient balance
Programs continue!

Throw vs Throws in Java:

throw keyword in Java can be used to throw an exception. It can throw the exception explicitly while throws keyword in java is used for declaring an exception

A throw is used inside the method while throws are used with the body signature.

A throw is used to throw only one exception while we can declare multiple exceptions using throws.

A throw is used in either checked exceptions or unchecked exceptions while throws only are used in a checked exception.

Final vs Finally vs Finalize in Java:

The Final is a modifier that is applicable for classes, methods, and variables. If a class declared as final then we can’t extend that class, if a method declared as final we can’t override that method in the child class, if a variable declared as final we can’t change the value of that variable.

Finally is a block always associated with try-catch to maintain the cleanup code. finally block is always run whether the exception handled or not.

Finalize() is a method that is always invoked by the garbage collector just before destroying an object to perform clean-up processing.

Leave a Comment