Exception Handling in Java [With Examples]

Exceptions are the unwanted and unexpected event of a program that is never desired by a programmer but has to deal with it so many times. The bright side is that it is possible with the object-oriented language Java to mitigate those undesirable events through a concept called ‘Exception Handling in Java’. It does not repair the exception but provides an alternate way to deal with it.

There can be many reasons for an exception to occur including entry of incorrect data, hardware failure, connection failure, server down, etc. Thus, exception handling is and always will be important in the course of learning Java as it helps to assure the normal flow of a program at the time an unexpected event occurs. Ignoring exceptions may cause the entire software to crash and may result in loss of data.

Now that we got an idea about exceptions and exception handling, let’s dive into it in detail and also understand how Java helps in handling exceptions.

Read: Exception Handling Interview Questions

What is Exception Handling?

A developer can predict the exceptions that a piece of code can throw during runtime. One of the most important things that many of the learners get ambiguous about is that all the exceptions occur during runtime and not at the time of compilation. Java can handle exceptions during runtime only. There are certain keywords used in a java program for creating an exception handler block.

java.lang.Exception is the parent class of all the exception classes. The Exception class is a subclass of the built-in Throwable class which is a subclass of the Object class. Apart from Exception, Throwable also has another class i.e Error which is an abnormal condition during the program execution which cannot be handled by Java programs which are the main difference between Error and Exceptions.

As shown in the above figure, there are mainly two categories of Exceptions in Java. In the next section, we will have a detailed look at the types of exceptions in Java.

Java Exceptions

The root causes of exceptions are the ones caused by the programmer or by physical resources that have failed due to some reasons. Based on these, there are mainly two categories of Exceptions in Java as below details of which are followed:

  1. Checked exception
  2. Unchecked exception

1. Checked Exception

Checked exceptions are known as the ‘compile-time exceptions’ as they are checked during compilation by the compiler to monitor if the exception is handled by the programmer. The system then displays a compilation error.

Some examples of these exceptions are IOException, SQLException, NoSuchMethodException, or ClassNotFoundException.

Read: Java Project Ideas for Beginners

2. Unchecked Exception

Unchecked exceptions are called ‘Runtime exceptions’ as they occur during the runtime of the program. Unchecked exceptions are normally ignored during the compilation and are not checked.

Examples of these exceptions can be bugs in a program such as logical errors, or using incorrect APIs which are not in the control of a programmer and require a system administrator to rectify.

Checked Vs Unchecked Exception

Differentiating Points Checked Exception or Compile-Time Exception Unchecked Exception or Run-Time Exception
Handling time Checked Exceptions are checked and handled at the time of compilation. Unchecked Exceptions are not checked at the time of compilation.
Exception Identification The program gives a compilation error if a method throws a checked exception. The program compiles fine as the compiler cannot check the exception.
Inheritance They do not inherit the RuntimeException class. They are the subclasses of RuntimeException class.
Developer’s Role Can be handled by the developers. Cannot be handled by the developers.

 

Understanding the exceptions is the primary step before handling them.

How does Java help in Handling Exceptions?

Now that we know there are two types of exceptions in Java viz., checked and unchecked. If a method is throwing a checked exception, it should be handled with a try-catch block or the ‘throws’ keyword should be declared to avoid compilation error in a program.

Example of a Checked Exception:

This is a program of reading a file named ‘Java’. There are three places where a checked exception is thrown:

  1. FileInputStream: Used for specifying the file path and name throw FileNotFoundException.
  2. The read() method: Reading the file content throws IOException;

      iii. The close() method: Closing the file input stream throws IOException.

import java.io.*;

class Example

   public static void main(String args[])

   {

            FileInputStream fis = null;

            /*The constructor FileInputStream(File filename)

            * throws a checked exception FileNotFoundException */

     fis = new FileInputStream(“B:/java.txt”);

            int k;

 

            /* Method read() of FileInputStream class throws

            * a checked exception: IOException

      */

            while(( k = fis.read() ) != –1)

            {

                            System.out.print((char)k);

            }

 

            /*The method close() closes the file input stream

            * throws IOException*/

            fis.close();         

   }

}

Output Of The Above Program:

Exception found in thread “main” java.lang.Error: Unresolved compilation problems:

Unhandled exception FileNotFoundException found

Unhandled exception IOException found

Unhandled exception IOException found

The reason for this compilation error: Non-declaration or handling of the exceptions.

Must Read: Java GitHub Projects

Methods of Exception Handling

There are two ways by which the exceptions can be handled described as below:

Method 1: Declaring the ‘throws’ exception keyword

In the above program, all three checked exceptions are inside the main() method. Thus, one way to avoid the compilation error is to declare the exception in the method using the ‘throws’ keyword. As IOException is a parent class of FileNotFoundException, it will cover that too.

Updated Program using throws keyword:

import java.io.*;

class Example

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

   {

   FileInputStream fis = null;

   fis = new FileInputStream(“B:/java.txt”);

   int k;

 

   while(( k = fis.read() ) != –1)

   {

              System.out.print((char)k);

   }

      fis.close();   

   }

}

 

Output:

Display the content of the file on the screen.

Method 2: Handle exceptions using try-catch blocks.

This is a more advanced approach to the above one and one of the best exception handling practices. The changed program code including the try-catch blocks is as follows:

import java.io.*;

class Example

   public static void main(String args[])

   {

            FileInputStream fis = null;

            try{

            fis = new FileInputStream(“B:/java.txt”);

            }catch(FileNotFoundException fnfe){

         System.out.println(“The file is not “ +

                                           “present at the path specified”);

            }

            int k;

            try{

            while(( k = fis.read() ) != –1)

            {

                            System.out.print((char)k);

            }

            fis.close();

            }catch(IOException ioe){

            System.out.println(“I/O error “+ioe);

            }

   }

}

 Output:

This code will eventually display the file content.

Example of an Unchecked Exception

The Unchecked exceptions are not checked at the time of compilation. The program won’t give a compilation error if it is not declared or handled and will run fine. The developer’s job is to predict the conditions that may occur in advance causing such exceptions and handle them. All Unchecked exceptions are subclasses of RuntimeException class.

class Example

   public static void main(String args[])

   {

            int num1=10;

            int num2=0;

            /*Dividing any number with 0

            * Will throw ArithmeticException

      */

            int res=num1/num2;

            System.out.println(res);

   }

}

 

The code will compile successfully with this code but during runtime, it would throw ArithmeticException as the unchecked exceptions are not checked at compile-time. Let’s take a look at another example.

class Example

   public static void main(String args[])

   {

            int arr[] ={1,2,3,4,5};

            /* The array has 5 elements but we want to

      * display the 8th element value. It will throw

            * ArrayIndexOutOfBoundsException

      */

            System.out.println(arr[7]);

   }

} 

This code will also compile successfully as ArrayIndexOutOfBoundsException is an unchecked exception.

Here, for handling Unchecked Exceptions, there should be an exception message displayed to the user which he wants to display, but it doesn’t exist in the array.

Handling the above code exception with try-catch block

class Example

   public static void main(String args[]) {

            try{

              int arr[] ={1,2,3,4,5};

              System.out.println(arr[7]);

            }

     catch(ArrayIndexOutOfBoundsException e){

              System.out.println(“The specified index does not exist “ +

                            “in the array.”);

            }

   }

}

 Output:

The specified index does not exist in the array.

 Note: There can be multiple catch blocks inside a try block for handling different exceptions.

Method 3: Using ‘finally’ keyword

Sometimes it happens that a code needs to be executed even if an exception occurs. This is where the final keyword is used. Here is a typical code with the ‘finally’ keyword.

 

public int getPlayerScore(String playerFile)

throws FileNotFoundException {

Scanner contents = null;

try {

contents = new Scanner(new File(playerFile));

return Integer.parseInt(contents.nextLine());

} finally {

if (contents != null) {

contents.close();

}

}

}

 

Here, the final block indicates the code we want Java to run when trying to read the file.

Even if a FileNotFoundException is thrown, Java will call the contents of finally.

We can handle the exception by modifying the code as below:

public int PlayerScore(String playerRuns) {

Scanner contents;

try {

contents = new Scanner(new File(playerRuns));

return Integer.parseInt(contents.nextLine());

} catch (FileNotFoundException noFile ) {

logger.warn(“File not found.”);

return 0;

} finally {

try {

if (contents != null) {

contents.close();

}

} catch (IOException ioexc) {

logger.error(“The reader could not be closed.”, ioexc);

}

}

}

Conclusion

With this article, we have tried to take through the basics of errors and exceptions and exception handling in Java. We hope this guide will give you a good idea of this unique feature that Java offers and you can now handle the exceptions and recover from them better.Conclusion

Java provides ways to handle exceptions right from specific to generic ones. Exceptions that cannot be predicted easily in advance are called unhandled exceptions. Capturing all the exceptions offers visibility to the development team on the quality of the code and the root causes of the errors which can be fixed quickly.

 If you’re interested to learn more about Java, full stack development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development. It is carefully curated for professionals and assures 360 degree career support and includes live projects to work on. By the end of the course, you will be able to design and build applications like Swiggy, IMDB, etc. 

Doesn’t that sound exciting!-

Become a Full Stack Developer

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN SOFTWARE DEVELOPMENT
Learn More

Leave a comment

Your email address will not be published. Required fields are marked *

×