Exception Handling in Java

Java's exception handling is one effective method for handling runtime failures and preserving the application's regular flow. The exception is a condition in Java where a program stops abruptly. This can be due to any arithmetic error or programming issue. To handle this, we need the methods of exception handling. In this article, we will be talking about exception handling in-depth and why it is important to handle exceptions in Java. We will also talk about various methods of exceptions such as try, catch, finally, throw, etc. along with the list of exceptions in Java.

Exceptions in Java

Java code execution may encounter a variety of mistakes, including programming flaws, input errors, and other unforeseen circumstances.Java typically stops and produces an error message when an error occurs. Java would throw an error or will throw an exception is the actual term for this.The program's usual flow is interrupted by an exception, which causes the program or application to end improperly. Since this is not ideal, these exceptions must be managed.

Numerous factors can lead to an exception. Here are various situations where an exception happens:

  • A user entered incorrect information.
  • Unable to locate a file that requires to be opened.
  • The JVM has run low memory or internet connectivity has been dropped in the midst of a communication.

 Become a Java Certified professional by learning this HKR Java Training !

Exception Handling in Java

A way to manage runtime problems like IOException, RemoteException, ClassNotFoundException,  SQLException,  etc. is called the process of exception handling. It is very important that the user handles exceptions at the right time.  A few methods for handling exceptions in Java are listed below.

  • Try, catch block
  • finally block
  • throw & throws block

Reasons why exceptions occur

  • User input is invalid
  • Network connection issue
  • Errors in the code
  • Opening of an empty/unavailable file
  • Failure of device
  • Disk memory failure 

Why handle Exceptions?

Exception Handling in Java exception handling is essential because it supports preserving the program's usual, desired flow even in the face of unexpected events. Requests may fail or programs may crash in case Java exceptions ain’t handled. Customers may find this extremely aggravating, and if it keeps happening, you risk losing them.

If your application breaks while the user is performing any crucial tasks, specifically if the content is lost, it is the worst-case scenario. Handling Java exceptions is crucial to ensuring the user interface is reliable and preventing unexpected application crashes and data loss. A sudden system crash may have a number of causes, such as incorrect or unforeseen data input. For instance, since the operation would compromise the integrity of the database, you must throw an error if we attempt to add two people to it with duplicate IDs.

To gently recover from those exceptions, it is best to explicitly manage them. Programming languages offer strategies to manage exceptions, starting with the more particular ones and working toward the more general ones, as we will see in the following sections. Unhandled exceptions in Java are those that are difficult to anticipate in advance. In order to recover gracefully, it's beneficial to capture these as well. Your development team will be able to see the integrity of the Java code and what is creating these mistakes so they may solve them more quickly by centrally tracking these Java exceptions.

Java Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Exception Class Hierarchy

The java.lang Exception class is a supertype of all exception classes. The Throwable class has a subclass called an exception. There is an additional subclass named Error that is descended by the Throwable class in addition to the exception class.

Errors are anomalous circumstances that occur in the situation of serious failures; Java applications are unable to handle these. Errors are produced to show errors that the runtime environment has produced. JVM runs out of memory, for instance. Programs typically never fix problems.

Exception Class Hierarchy

The 2 main subclasses of exception class are RuntimeException Class and  IOException class.

Types of Exceptions

Let us also understand the categories of exceptions in the section below:

1. Checked exceptions: They are also known as compile time exceptions, and are verified by the computer during compilation. The programmer must take care of (manage) these exceptions; they cannot just be ignored.
Let us see the Java program below for checked exceptions:

import java.io.File;

import java.io.FileReader;

public class File_not_Found_Demo {

   public static void main(String args[]) {

      File f = new File("E://file.txt");

      FileReader fr = new FileReader(f); 

   }

}

The output will be:

File_not_Found_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown

                      ^
1 error

2. Unchecked exceptions: An exception that happens during execution is known as an unchecked exception. These also go by the name of runtime exceptions. These include programming flaws like logical mistakes or inappropriate API usage. Runtime exceptions are not taken into account during compilation.

Let us see the pJava program below for unchecked exceptions:

public class UncheckedDemo {

      public static void main(String args[]) {

      int number[] = {10, 20, 30, 40};

      System.out.println(number[5]);

   }

}

The output will be:

java -cp /tmp/dJyKb6kw4D UncheckedDemo

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4at UncheckedDemo.main(UncheckedDemo.java:5)

3. Errors: These are issues that develop for reasons beyond the user's or the programmer's control, with no exceptions at all. Because there is rarely anything you can do about an error, errors are often disregarded in your code. For instance, a stack overflow will result in an error. During the period of compilation, they are also disregarded.

Handle Exceptions in Java

The try block

The simplest approach to handling exceptions is try-catch. Put an exception in  Java that the code throws in the try block, and one or more catch blocks will capture them.

All types of Java exceptions will be caught by this function. The simplest method of handling exceptions is this one.

try {

  // code block that throws exceptions

} catch (Exception E) {

  // The exception handler

}
The catch block

Additionally, you can be more specific about the exceptions you want to catch. This enables you to have specific code to fix particular faults. For instance, some Java faults given by a REST API can be resolved while others cannot. This enables you to handle such ailments independently.

When more than one catch block, each of which specifies a distinct type, may come after a try block. It will then run the initial catch block that deals with the exception type or any of its superclasses. So, be careful to attend the lesson that is the most specific initially.

try {

 // code block that throws exceptions

} catch (Exception_Type_1 E1) {

  // The exception handler for Exception_Type_1

} catch (Exception_Type_2 E2) {

// The exception handler for Exception_Type_2

}
The finally block

A finally block is used for any code that needs to run regardless of whether an exception occurs. We can also say the finally block is will be the one always carried out. For instance, if the try block throws an exception in Java, use the finally block to kill the connection to the database or file if you have one open.

try {

 // code block that throws exceptions

} catch (Exception_Type_1 E1) {

  // The exception handler for Exception_Type_1

} catch (Exception_Type_2 E2) {

// The exception handler for Exception_Type_2

} finally {

  // The finally block will always execute

}
Throw block

In Java, an exception can be thrown explicitly using the throw keyword.

The exception object that is to be thrown is specified. The notice that comes with the exception contains a description of the error. These anomalies could be caused by user inputs, the server, etc.

Java's throw keyword allows us to throw either verified or unchecked exceptions. It mostly serves as a custom exception thrower. The syntax of the throw keyword is given below:

throw new Class_exception("error_message");  

Additionally, we can use the throw keyword to specifically throw an exception and establish our own set of circumstances. For instance, dividing a no by another no may result in the throwing of an ArithmeticException. Here, we simply have to specify the criteria and use the throw keyword to raise an exception.

Let us see a Java program below to understand throw block:

public class TestThrow1 {  

    public static void validate(int age) {  

        if(age<18) {  

            throw new ArithmeticException("A man cannot vote");    

        }  

        else {  

            System.out.println("A man can vote");  

        }  

    }  

    public static void main(String args[]){  

        validate(14);  

        System.out.println("The rest is extra code");    

  }    

}    
The output of this Java code will be:
Exception in thread "main" java.lang.ArithmeticException: A man cannot vote

at TestThrow1.validate(TestThrow1.java:4)

at TestThrow1.main(TestThrow1.java:12)
Explore Scala Sample Resumes Download & Edit, Get Noticed by Top Employers! 

Catching Specific Java Exceptions

The code that is enclosed tends to have the potential of raising an exception, as indicated by the try keyword. The try clause is followed by the catch block, which specifies the exception that will be caught. A compiler error will be produced if a checked exception does not have a catch clause.

Let us see the Java code below to understand the catching of exceptions in Java in a better manner:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;


public class File

{

public static void main(String[] args)

{

BufferedReader B = null;

FileReader F = null;

try

{

F = new FileReader("C:\\JIP\\test.txt");

B = new BufferedReader(F);


String text;

while ((text = B.readLine()) != null)

System.out.println(text);

} catch (FileNotFoundException e)

{

e.printStackTrace();

}

}

}
The output of the Java code is:
.java

error: invalid flag: /tmp/dJyKb6kw4D/File

Usage: javac


use --help for a list of possible options

dash: 2: .java: not found

Catching Multiple Exceptions

There may be instances where a specific piece of code has a propensity to raise several exceptions. Within a try block, you should catch all potential exceptions that might arise. There are two methods to approach this situation.

1. By multiple catch blocks

When numerous exceptions can happen within the same block or more than one catch block can be supplied. Every catch block has distinct exception handling options and can capture different types of exceptions.

Let us see the Java code below to understand this better:

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class File

{

public static void main(String[] args)

{

BufferedReader B = null;

FileReader F = null;

try

{

F = new FileReader("C:\\JIP\\test.txt");

B = new BufferedReader(F);

String text;

while ((text = B.readLine()) != null)

System.out.println(text);

} catch (FileNotFoundException fe)

{

fe.printStackTrace();

} catch (IOException ie)

{

System.out.println("The IOException has occured");

}

}

}


Two catch clauses have been added to the code above.

Catching FileNotFoundException and reporting the stack trace will be the first one.

The message "IOException has occurred" will be printed by the second one, which will be catching IOException.

 Want to know more about Java,visit here Java J2EE Tutorial !

Subscribe to our youtube channel to get new updates..!

2. Catching multiple exceptions in one catch block

The pipe symbol "|" can be used to divide exceptions if more than one exception needs to be caught and handled in one catch block.

Let us see the Java code below to understand this better:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class File

{

public static void main(String[] args)

{

BufferedReader B = null;

FileReader F = null;

try

{

F = new FileReader("C:\\JIP\\test.txt");

B = new BufferedReader(fr);

System.out.println(1/0);

String text;

while ((text = B.readLine()) != null)

System.out.println(text);

} catch (IOException | ArithmeticException e )

{

e.printStackTrace();

}

}

}

The code above handles both the IOExceptions and the ArithmeticException exceptions and executes the identical action [print stack trace] for each error.

3. Catching all the exceptions

What will happen if another exception, such as NullPointerException, occurs if, assumable, the code above only managed to catch IOExceptions and ArithmeticException. Because we don't have a catch block for NullPointerException, the application will terminate abnormally.

All you need to do to avoid this circumstance is add one more catch to the exception base class [Exception or Throwable]. Since it's the parent class of all exceptions, the catch block tends to capture every exception.

Let us see the Java code below to understand this better:

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class File

{

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

{

BufferedReader B = null;

FileReader F = null;

try

{

F = new FileReader("C:\\JIP\\test.txt");

B = new BufferedReader(F);

String text;

while ((text = B.readLine()) != null)

System.out.println(text);

} catch (FileNotFoundException f)

{

f.printStackTrace();

} catch (IOException ie)

{

System.out.println("The I/OException has occured");

} catch (Exception e)

{

e.printStackTrace();

}

finally

{

if (F != null)

F.close();

if( B != null)

B.close();

}

}

}

In the finally block, we are shutting the opened resources, such as FileReader and BufferedReader.

Explore R Sample Resumes Download & Edit, Get Noticed by Top Employers! 

List of Exceptions in Java

A list of the most common Java exceptions is provided below. For some of these exceptions, programming examples have been given. Keep in mind that Java supports them as built-in exceptions.

1.ArithmeticException

ArithmeticException is the outcome of arithmetic anomalies like dividing by zero.

Let us see the Java code below to understand arithmetic exceptions better:

class Main { 

public static void main(String args[]) 

    { 

        try { 

            int number1 = 10, number2 = 0; 

            int res = number1 / number2;

            System.out.println("Result will be = " + res); 

        } 

        catch (ArithmeticException e) { 

            System.out.println("ArithmeticException: Division by Zero"); 

        } 

    } 

}

The output of this Java code will be:

java -cp /tmp/dJyKb6kw4D Main

ArithmeticException: Division by Zero
2.ArrayIndexOutOfBoundsException

When an element of the array is accessed using an improper index, an ArrayIndexOutOfBoundsException is raised. The used index is either negative or exceeds the array's size. 

3. ClassNotFoundException

This exception is raised if the class definition cannot be located.

4.FileNotFoundException

This error message is displayed when a file cannot be opened or does not exist.

5.IOException

When an input-output operation fails or is halted, IOException is raised.

6.InterruptedException

A thread when interrupted, it is processing data, sleeping, or waiting by throwing an InterruptedException.

7.NoSuchFieldException

This exception is thrown when a class lacks a required field or variable.

8.NoSuchMethodException

This exception is raised whenever the method is accessed and cannot be found.

9.NullPointerException

When a null object is referenced, a NullPointerException is raised. The most significant and typical Java exception is this one.

10. RuntimeException

A RuntimeException is any exception that happens during runtime.

11.StringIndexOutOfBoundsException

The String class can throw the StringIndexOutOfBoundsException if the index is either negative or exceeds the size of the String object.

12.EOFException

When the end of a file is reached while the file has been read, the java.io package's EOFException is issued.

13. IllegalArgumentException

Illegal or incorrect arguments are supplied to a method and cause an IllegalArgumentException to be produced. For instance, the incorrect data format, a null value when a non-null value is required, or out-of-range arguments

14.InputMismatchException

Once the input data read does not match the required pattern, an InputMismatchException is raised. For instance, the InputMismatchException is thrown if a float value is an input when the program is expecting an integer.

15.NoSuchElementException

NoSuchElementException is raised if the element being accessed after it does not exist.

Top 60 frequently asked Java Interview Questions !

Java Certification Training

Weekday / Weekend Batches

Conclusion

In this article, we have discussed various exceptions in java and the method to handle the exceptions. An exception is defined as when Java code execution may encounter a variety of mistakes, including programming flaws, input errors, and other unforeseen circumstances. A way to manage runtime problems like IOException, RemoteException, ClassNotFoundException,  SQLException,  etc. is called the process of exception handling. It is very important that the user handles exceptions at the right time.  A few methods for handling exceptions in Java are listed as Try, catch block and finally block. We have also discussed the methods and various types of exceptions in Java along with their example. 

Related blogs:

Find our upcoming Java Certification Training Online Classes

  • Batch starts on 24th Mar 2023, Fast Track batch

  • Batch starts on 28th Mar 2023, Weekday batch

  • Batch starts on 1st Apr 2023, Weekend batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.

A way to manage runtime problems like IOException, RemoteException, ClassNotFoundException,  SQLException,  etc. is called the process of exception handling

Try, catch, finally, throw, and throws are the 5 important keywords in exception handling in Java

An exception is defined as when Java code execution may encounter a variety of mistakes, including programming flaws, input errors, and other unforeseen circumstances.

The exception is basically an error that comes during the execution of a Java code however exception handling is the process to overcome that abnormality to resume the successful execution. 

There are 2 main types of exceptions in Java: checked and unchecked

The advantages of exception handling in Java are:

  • Segregating error code from the executable code
  • Errors Spreading Up the Call Stack.
  • Error Differentiation and Error Types are grouped.
Protected by Astra Security