Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Exception Handling in Java [With Examples]

Updated on 15 November, 2022

7.19K+ views
10 min read

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.

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.

Check out upGrad’s Java Bootcamp

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.

Check out upGrad’s Advanced Certification in Blockchain

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.

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

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

Frequently Asked Questions (FAQs)

1. What 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.

2. Should 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.

3. Does 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.

RELATED PROGRAMS