What is Exception Handling in Java?

Exception Handling in Java is a distinctive approach to improvise a Java application's convenience and performance capabilities. Exceptions, if not handled properly, may pose a severe threat to the application program in real-time. 

Let us learn more about exceptions and how to handle them, to make sure the Java application is safe and secure. 

What is an Exception?

Exception-Handling-in-Java

An Exception is an unexpected event that may occur during the program's compile-time or run-time. It is capable enough to cause a severe potential threat and disrupt the entire flow of the program.

Now you might be wondering, an error does the same thing, But it is a lot more different. We will learn more about the "error" in the next section.

What is an Error?

What-is-an-error-Exception-Handling-in-Java

An exception will disturb the normal flow of any runnable program. But an error is something that contributes to making a program not capable of executing and sometimes collapse as well.

Now, an Error can be defined as follows.

An error can be defined as a state at which the computer program cannot recover, and stays in a non-executable mode or sometimes collapses from normal-execution.

To have a clear understanding of an Exception and an Error, we shall now learn the differences between them.

Error vs Exception

Error-vs-Exception-Exception-Handling-in-Java.

Error

Exception

Library: java.lang.Error

Library: jav.lang.Exception

Errors are of Unchecked type

Exceptions are both Checked and Unchecked type

The compiler can not understand errors

The compiler identifies checked exceptions

Errors are mainly encountered in the run-time

Only the unchecked exceptions are encountered in run-time

The program cannot recover from an error by itself

The program can recover from exceptions as the compilers add “try and catch” blocks automatically

The error may be caused by program logic or the run-time environment

An exception is caused by the application 

Now that we have a clear cut differentiation and a better understanding of both, let us move ahead and learn the Exception Hierarchy in Java.

Get Mentored by Leading Java Experts!

Full Stack Java DeveloperExplore Program
Get Mentored by Leading Java Experts!

Java Exceptions Use Cases

Java exceptions play a critical role in writing robust and reliable software applications. They provide a mechanism for handling unexpected or exceptional conditions that may arise during program execution. Understanding the various use cases for Java exceptions is essential for writing code that can gracefully recover from errors, provide meaningful feedback to users, and ensure the overall stability of the application.

Input Validation

One of the primary use cases for exceptions in Java is input validation. When a program receives input from external sources, such as user input or data from a file or network, it's crucial to validate that input to ensure it meets certain criteria or constraints. For example, if a method expects a positive integer as input but receives a negative number or a non-integer value, it can throw an IllegalArgumentException to indicate that the input is invalid.

Resource Management

Java exceptions are also commonly used for resource management, such as file I/O or database operations. When working with external resources, it's essential to handle exceptions that may occur due to factors such as file not found, permission denied, or database connection failure. By catching and handling these exceptions appropriately, developers can ensure that system resources are released properly and that the application maintains its integrity even in the event of resource-related errors.

Network Communication

In networked applications, exceptions are frequently used to handle errors that may occur during communication with remote servers or clients. For example, if a client application attempts to connect to a server but encounters a network timeout or server unreachable error, it can throw a SocketTimeoutException or UnknownHostException respectively. By catching and handling these exceptions, the application can provide feedback to the user or take appropriate action to retry the connection or notify the user of the error.

Concurrency

Exception handling is also important in multi-threaded and concurrent applications, where multiple threads may be executing simultaneously. Exceptions thrown by one thread can propagate to other threads if not handled properly, potentially causing the entire application to crash. To prevent this, developers use constructs like try-catch blocks and Thread.UncaughtExceptionHandler to catch and handle exceptions at the appropriate level and ensure that the application remains stable even in the presence of concurrent execution.

Custom Error Conditions

Finally, Java exceptions can be used to represent custom error conditions or exceptional situations specific to a particular application or domain. By defining custom exception classes that extend Exception or one of its subclasses, developers can encapsulate error-specific information and provide a standardized way to handle those errors throughout the application. This allows for more granular control over error handling and enables developers to communicate error conditions effectively within the codebase.

Exception Hierarchy

Exception-Hierarchy-Exception-Handling-in-Java

The Hierarchy of Exceptions in Java is not too complicated. All the errors and exceptions are inherited from the parent class called ‘Throwable’. Two sub-classes inherit the throwable class. One is the Error class, and the other is the Exception class.

Now, these two classes are further inherited by a few more errors and exceptions, which are shown clearly in the image below.

Now, that we have better clarity on the Exception Hierarchy, we will be briefly looking into the types of Exceptions. For a better experience, let us enter into the next section, which describes the various types of Java exceptions.

Types of Exceptions  

There are technically two types of Exceptions, and the third variety is an error. Those are mentioned below as follows.

  • Checked Exceptions 
  • Unchecked Exceptions
  • Errors

Checked Exceptions 

The classes that inherit all the exceptions from the throwable parent class directly, but except for the run-time exception, are called the checked exceptions.

Example:

SQL Exception and IOException

//code 1:

//Checked exception (unresolved)

package Exceptions;

import java.io.*;

public class Checked {

public static void main(String[] args) {

FileReader file = new FileReader("C:\\Users\\ravi.kiran\\Documents\\data.txt");

BufferedReader Input = new BufferedReader(file);

for (int c = 0; c < 3; c++)

System.out.println(Input.readLine());

Input.close();

}

}

//code 2:

//Checked exception (resolved)

package Exceptions;

import java.io.*;

public class Checked {

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

FileReader file = new FileReader("C:\\Users\\ravi.kiran\\Documents\\data.txt");

BufferedReader Input = new BufferedReader(file);

for (int c = 0; c < 5; c++)

System.out.println(Input.readLine());

Input.close();

}

}

Unchecked Exceptions

The classes that inherit only the run-time exceptions are called as the Unchecked Exceptions.

Example:

ArithmeticException and NullPointerException

//code:

Unchecked Exceptions(Resolved)

package Exceptions;

public class Unchecked {

public static void main(String args[]) {

int Ary[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

System.out.println(Ary[11]);

}

}

Errors

An unrecoverable event that collapses the entire application program is called as an error.

Example:

OutOfMemoryError and AssertionError

With this, we have a detailed understanding of the different types of Exceptions in Java. Moving further, for a much precise clarification on the two major types of exceptions, we will learn the apparent differences between both.

Checked Exceptions vs Unchecked Exceptions

checked-vs-unchecked-exceptions-Exception-Handling-in-Javachecked-vs-unchecked-exceptions-Exception-Handling-in-Java

The table below helps us with the differences between the Checked Exceptions and the Unchecked Exceptions.

Checked Exceptions

Unchecked Exceptions

Can be checked and handled during Compile-time

Cannot be checked nor be handled during Compile-time

Direct subclasses of exception class but do not inherit run-time exception

Direct subclasses of exception class but only inherits run-time exception

The compiler catches these exceptions in the compilation stage

The compiler cannot recognize and catch them during the compilation stage

Checked Exceptions are predictable failures

Uncheck exceptions are unpredictable failures, mostly caused by improper programming logic

Examples:

SQL Exception

IOException

Examples:

ArithmeticException

NullPointerException

So these were the evident differences between the Checked and Unchecked Exceptions in Java. Moving further, we will learn the crucial keywords necessary to carry over the exception handling process in Java.

Keywords for Exception Handling in Java

The following are the primary keywords used in the process of Exception handling in Java.

Keyword

Description

try

The “try” keyword is used to specify the exception block

catch

The “catch” keyword is used to specify the solution

finally

The “finally” keyword has a mandatorily executable code

throw

The “throw” keyword throws an exception

throws

The “throws” keyword is used to declare an exception 

With the keywords discussed, let us get into the central part of Exception Handling in Java. We will learn the methods of Exception Handling in Java.

Methods for Exception Handling in Java

There are two ways for Exception Handling in Java. They are as follows.

  • Default Exception Handling in Java
  • User-Defined Exception Handling in Java

Default Exception Handling in Java

Java Virtual machine handles default exceptions. The compiler identifies the presence of an exception, it quickly packs the recognized exception in the form of an object. 

The compiler sends the exception object to the JVM during the run-time. This process is called throwing an Exception. 

After the exception is thrown, many methods could get executed in response to the thrown exception. The list is known as the Call Stack. The Call Stack is described as follows.

  • The thrown exception reaches the call stack, and the call stack responds with an exception handler that could handle the thrown exception.
  • If the run-time system fails to recognize the appropriate exception handler for the thrown exception, then the run-time system sends the exception object to the default exception handler. 
  • The default exception handler results in an abnormal output that reads out a report related to the bizarre exception encounter.

Get Mentored by Leading Java Experts!

Full Stack Java DeveloperExplore Program
Get Mentored by Leading Java Experts!

User-Defined Exception Handling in Java

The customized/user-defined exception handling in Java is managed by using the exception handling keywords. They are:

  • try
  • catch
  • throw
  • throws
  • finally

In customized exception handling, the user should recognize/expect an exception at a specific part of the code segment. 

Once the location of the exception is finalized, then, the code block should be enclosed inside the try and catch blocks.

With this setup, whenever the code throws an exception, it gets handled by the appropriate catch block.

The "throw" keyword is used to manually throw an exception. When an exception is thrown from the program, it is identified by the "throws" clause.

Now that we have clarity on the exceptions and procedures for Exception Handling in Java, we will directly deal with some of the frequently faced exceptions in Java and resolve them programmatically.

Hierarchy of Java Exception Classes

In Java, exceptions are objects that represent an abnormal condition in the program flow. The Java language provides a rich hierarchy of exception classes, organized in a hierarchy to facilitate exception handling and management within programs. Understanding this hierarchy is crucial for effectively handling exceptions in Java applications.

At the top of the exception hierarchy is the Throwable class. All exceptions and errors in Java, whether checked or unchecked, are subclasses of Throwable. The Throwable class itself provides methods like getMessage() and printStackTrace() that allow access to information about the exception.

Directly below Throwable are two main subclasses: Exception and Error. Exceptions are conditions that occur because of problems in the code (such as invalid input or resource unavailability) and are expected to be caught and handled by the program. On the other hand, errors are exceptional conditions that are generally beyond the control of the program and typically indicate serious problems that should not be caught by ordinary application code.

The Exception class further subclasses into two main categories: checked exceptions and unchecked exceptions. Checked exceptions must be either caught by the code or declared in the method signature using the throws keyword. Examples of checked exceptions include IOException, SQLException, and ClassNotFoundException. Unchecked exceptions, also known as runtime exceptions, do not need to be explicitly caught or declared and typically result from programming errors such as null pointer dereferences or arithmetic overflows. Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.

Additionally, there are specialized subclasses of Exception that provide more specific information about certain types of exceptional conditions. For example, IOException is a subclass of Exception that represents input-output related errors, while RuntimeException is a subclass of Exception that serves as the superclass of all unchecked exceptions.

Under the Error class, there are subclasses that represent critical errors that usually cannot be handled by the application code and may lead to abnormal termination of the program. Examples of error subclasses include OutOfMemoryError, StackOverflowError, and VirtualMachineError.

Understanding the hierarchy of Java exception classes allows developers to implement appropriate exception handling strategies in their applications. By catching and handling exceptions effectively, developers can improve the robustness and reliability of their Java programs, leading to better user experiences and reduced downtime. Additionally, understanding the distinction between checked and unchecked exceptions helps developers design APIs and libraries that promote code safety and maintainability.

Common Exceptions in Java

array-out-of-bound-index-common-exceptions-Exception-Handling-in-Java.

Some of the common exceptions faced in the process of Exception Handling in Java are as follows.

ArrayIndexOutOfBound

When you try to store a value in the array location with an address exceeding the array's maximum location value, this exception is thrown. 

Example:

//ArrayIndxOutOfBound

package Exceptions;

import java.util.Arrays;

import java.util.Scanner;

public class IndexOutOfBound {

public static void main(String args[]) {

int[] Array = {(int) 10.0,(int) 20.0,(int) 30.0,(int) 40.0,(int) 50.0};

System.out.println("The array elemens are as follows: \n");

System.out.println(Arrays.toString(Array));

Scanner scan = new Scanner(System.in);

System.out.println("Please provide the address of the required element:\n");

float numbers = scan.nextFloat();

System.out.println("Number at your selected address is "+Array[(int) numbers]);

}

}

NullPointer Exception

When you perform a Mathematical operation on a null value, then this exception is thrown. 

Example:

//NullPointer

package Exceptions;

import java.util.Arrays;

import java.util.Scanner;

public class NullPointer {

private static String str;

public static void main(String[] args) {

str = "simplilearn";

foo(null);

bar(null);

}

static void foo(String abc) {

try {

System.out.println("First character in the string is:\n" + abc.charAt(0));

} catch (NullPointerException e) {

System.out.println("NullPointerException!");

}

}

static void bar(String abc) {

if (abc == null)

System.out.println("First character in the string is:\n " + abc.charAt(0));

else

System.out.println("NullPointerException!");

}

}

NumberFormat Exception

If you try to store a value with the wrong number format, like a different datatype, then this exception is thrown. 

Example:

//NumberFormatted

package Exceptions;

public class NumFormat {

private static int num;

public static void main(String[] args) {

num = Integer.parseInt(null);

}

}

DividebyZero Exception

In case if you try to divide a number by zero, this exception is thrown. 

Example:

//Divide by zero

package Exceptions;

public class DBZ {

public static void main(String args[]) {

int n1, n2;

try {

n1 = 0;

n2 = 100 / n1;

System.out.println(n2);

} catch (ArithmeticException e) {

System.out.println("The divider cannot be zero, try a differnt number.");

} catch (Exception e) {

System.out.println("You cannot execute this program: DivideByZeroException");

}

}

}

So far, we have dealt with different types of exceptions and other procedures for Exception Handling in Java. Now we will learn the best practices to be followed for Exception Handling in Java in the next section.

Best Practices for Exception Handling in Java

best-practices-Exception-Handling-in-Java

After we have learned the frequently faced exceptions in Java, we will now understand the best practices to be followed while implementing Exception Handling procedures in Java.

  • Use exceptions conservatively
  • Customized exceptions
  • Exceptions logging
  • Early throw and fail
  • Closing resources

Use Exceptions Conservatively

use-exceptions-coversatively-best-practices-Exception-Handling-in-Java

Exceptions have proven that they can be costly if used recklessly. We should use Boolean values to indicate the successful implementation of smaller operations.

Customized Exceptions

customized-exceptions-Exception-Handling-in-Java

It's an outstanding practice of customizing your exceptions in the design time rather than planning them on the go.

Exceptions Logging

exception-logging-Exception-Handling-in-Java

Keeping track of the exceptions comes handy as the user understands why a particular exception popped up.

Early Throw and Fail

early-throw-and-fail-Exception-Handling-in-Java

An exception is expected to be thrown as early as possible and should be resolved at the same pace.

Closing Resources

close-resources-Exception-Handling-in-Java

Since exceptions halt the complete program, we must ensure the system resources are shut to save the resources.

Get a firm foundation in Java, the most commonly used programming language in software development with the Caltech Post Graduate Program In AI And Machine Learning.

Get Mentored by Leading Java Experts!

Full Stack Java DeveloperExplore Program
Get Mentored by Leading Java Experts!

Next Steps

With this, we have now arrived at the end of the "Exception Handling in Java' article. We hope you enjoyed learning about the essential concepts of Interface in Java.

Exception Handling was only one of the crucial concepts for Software Development using Java. 

Are you looking for more about the Java Programming Language and getting certified as a professional Java Developer? Then, check out our Full Stack Java Developer Master's program. It is curated by the most experienced real-time industry experts.

Got a question about the "Exception Handling in Java" article? Please mention it in the comment section of this article, and we'll have our experts answer it for you right away.

FAQs

1. How to handle null pointer exception in Java?

To handle a NullPointerException in Java, you can use a try-catch block to catch the exception and handle it gracefully. Alternatively, you can use defensive programming techniques such as checking for null values before accessing object references to prevent the exception from occurring in the first place.

2. Can we handle runtime exception in Java?

Yes, runtime exceptions can be handled in Java using try-catch blocks just like checked exceptions. However, it's generally not recommended to catch and handle all runtime exceptions indiscriminately, as they often indicate programming errors that should be fixed rather than simply caught and ignored.

3. Can we handle unchecked exceptions in Java?

Yes, unchecked exceptions, which include runtime exceptions and errors, can be handled in Java using try-catch blocks. However, as with runtime exceptions, it's important to handle unchecked exceptions judiciously and only catch them if you can provide meaningful recovery or error-handling logic.

4. How many ways to handle exception in Java?

There are three main ways to handle exceptions in Java:

  • Using try-catch blocks to catch and handle exceptions.
  • Using the throws keyword to declare exceptions in method signatures and propagate them to the calling code.
  • Using the finally block to execute cleanup or resource release code regardless of whether an exception occurs.

5. How do you handle exceptions in OOP?

In object-oriented programming (OOP), exception handling is typically implemented using inheritance and polymorphism. You can define custom exception classes that extend the built-in exception classes provided by Java, allowing you to create a hierarchy of exception types tailored to your application's specific needs. By catching and handling exceptions at appropriate levels of abstraction in your object-oriented design, you can encapsulate error-handling logic within the relevant classes and promote code reusability and maintainability.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.