Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconException Handling in Java [With Examples]

Exception Handling in Java [With Examples]

Last updated:
11th Nov, 2020
Views
Read Time
10 Mins
share image icon
In this article
Chevron in toc
View All
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.

Check out our free courses to get an edge over the competition.

Ads of upGrad blog

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.

Explore our Popular Software Engineering Courses

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.

Check out upGrad’s Java Bootcamp

Checked Vs Unchecked Exception

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

Check out upGrad’s Advanced Certification in Blockchain

Understanding the exceptions is the primary step before handling them.

Explore Our Software Development Free Courses

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

   }

}

In-Demand Software Development Skills

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.

Read our Popular Articles related to Software Development

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

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

Ads of upGrad blog

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!-

Profile

Sriram

Blog Author
Meet Sriram, an SEO executive and blog content marketing whiz. He has a knack for crafting compelling content that not only engages readers but also boosts website traffic and conversions. When he's not busy optimizing websites or brainstorming blog ideas, you can find him lost in fictional books that transport him to magical worlds full of dragons, wizards, and aliens.

Frequently Asked Questions (FAQs)

1What exactly is an exception in a programming language?

In programming, an exception can be any kind of unplanned or unforeseen event that occurs during runtime and disrupts the natural course of the program execution. An invalid or unacceptable input or a sudden drop in network connectivity are the most common examples of an exception. Programmers develop code modules to handle exceptions, such that the flow of the program remains uninterrupted. But there might be unchecked exceptions – those which occur during the compilation phase of the program and cannot be handled. Such exceptions are fatal since they prompt the operating system to force close the program. Errors are typical examples of unchecked exceptions.

2Should exceptions be used at all times?

Exception handling offers a graceful method of dealing with a sudden problem in the flow of a program. There are some standard cases when it is essential or rather mandatory to use exceptions. For instance, use exception handling only in exceptional conditions, like, when something cannot be recovered. A program riddled with many exceptions is undesirable and becomes too expensive to maintain. Exceptions should ideally be used to deal with external problems, like connectivity issues with the database. But, there are also times when you should not use an exception. For example, exceptions should never be used to control the flow of program logic.

3Does C programming language support exception handling?

The C programming language does not offer direct means of exception handling or even error handling. But it is possible to write code for error and exception handling in C. To make this possible in C, a programmer must ensure error-free coding and validate values returned by the functions they code. Many C functions return NULL or -1 in case of errors. So writing code to test the values is the best way to detect and handle errors. Different error handling methods in C include functions like perror() and strerror(), EXIT_SUCCESS, EXIT_FAILURE, errno global variable, and divide by zero error.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 7 Node js Project Ideas & Topics
31569
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46924
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers & Experienced]
901322
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners & Experienced]
52078
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers & Experienced]
909174
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34743
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers & Experienced]
902385
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26212
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions & Answers [2024]
4382
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon