Exception Handling in Java
Exception Handling in Java is an effective method for dealing with unwanted and unexpected events during program execution
while maintaining the application's usual flow. When learning Java, one must be ready to deal with errors, unexpected inputs, or
other exceptions.
What is an Exception in Java?
Exceptions are unwanted events that disrupt the program's execution. Many a time, your program looks error-free after writing
the code. But, at the time of execution, some unexpected errors or events or objects come to the surface, and the program prints
an error message and stops executing. Such unexpected happenings are called exceptions in Java.
There are some specific reasons why exceptions occur in Java:
User’s Invalid Input
Database Connection Error
System Failure
Network Problem
Security Compromises
Errors in Code
Physical Limitations
What is Exception Handling in Java?
Exception Handling is a way of handling errors that occur during runtime and compile time. It maintains your program flow despite
runtime errors in the code and, thus, prevents unanticipated crashes. It facilitates troubleshooting by providing error details,
cutting down on development time, and improving user happiness.
Exception Hierarchy in Java
Exception and Error are subclasses of Throwable, the hierarchy's base class. Exception, for example, is used for exceptional
conditions that user programs should catch. Error, on the other hand, is used by the Java run-time system (JVM) to indicate errors
related to the run-time environment (JRE), such as StackOverflowError.
The hierarchy is divided into two branches:
1. Errors: An error is a severe condition that can occur only at run time and is irrecoverable. It prevents a program from
executing and cannot be handled by the programmer. An error belongs to the java.lang.error class.
2. Exceptions: A programmer can catch and handle exceptions in his program code. When an exception occurs within a
method, an object called the exception object is created. This object contains information about the exception, such as its
name and description and the state of the program when the exception occurred.
We'll look at the types of exceptions below:
Types of Exceptions in Java
There are mainly two types of exceptions: user-defined and built-in.
1. Built-in Exceptions
These exceptions are present in Java libraries.
There are two types of built-in exceptions in Java:
1. Checked Exception
Checked exceptions are classes that inherit directly from the Throwable class, with the exception of RuntimeException and Error.
Examples include IOException, SQLException, and so on. Checked exceptions are checked at compilation time. They must be either
caught by the code or declared in the method signature using the throws keyword.
2. Unchecked Exception
Classes that inherit the RuntimeException class are known as unchecked exceptions. Examples include ArithmeticException,
NullPointerException, and ArrayIndexOutOfBoundsException. Unchecked exceptions are not checked at compile-time but rather at
runtime by JVM. They do not need to be explicitly caught or declared.
2. User-Defined Exceptions
User-defined exceptions are also known as custom exceptions derived from the Exception class from java.lang package. The user
creates these exceptions according to different situations. Such exceptions are handled using five keywords: try, catch, throw,
throws, and finally.
We'll learn how to use these keywords in the Exception Handling Keywords in Java section below.
Errors Vs. Exceptions in Java
Errors Exceptions
Belongs to the java.lang.Error class defined in java.lang.Exception package
Errors are of Unchecked type Exceptions can be both checked and unchecked.
Errors mainly occur during run-time. Only the unchecked exceptions are encountered in run-time.
Errors are irrecoverable Exceptions can be handled using exception-handling mechanisms
Java Exception Handling Keywords
Java consists of five keywords to handle various kinds of custom exceptions. They are:
Keyword Description
try The "try" keyword specifies an exception block.
catch specifies the code block to be executed if an exception occurs in the try block.
finally the finally block will always be executed whether an exception occurs or not
throw the "throw" keyword triggers an exception
throws The "throws" keyword declares an exception.
1. try
A try block consists of all the doubtful statements that can throw exceptions.
A try block cannot be executed on itself; it requires at least one catch block or finally block.
If an exception occurs, the control flows from the try-to-catch block.
When an exception occurs in a try block, the appropriate exception object is redirected to the catch block. This catch block
handles the exception according to its statements and continues the execution.
Syntax
try
//Doubtful Statements.
2. catch
The catch block handles the exception raised in the try block.
The catch block or blocks follow every try block.
The catch block catches the thrown exception as its parameter and executes the statements inside it.
The declared exception must be the parent class exception, the generated exception type in the exception class hierarchy,
or a user-defined exception.
Syntax
try
// code
catch(Exception e)
// code to handle exceptions
Examples IIlustrating Implementation of try-catch blocks for Java Exception Handling in Java Online Compiler
1. single try-catch block
2.
3. class Main
4. {
5. public static void main(String[] args)
6. {
7. try
8. {
9. // code that generate exception
10. int divideByZero = 5 / 0;
11. System.out.println("Rest of code in try block");
12. }
13. catch (ArithmeticException e) {
14. System.out.println("ArithmeticException => " + e.getMessage());
15. }
16. }
Run Code >>
In the above code, we have put the "int divideByZero=5/0" in the try block because this statement must not be executed if the
denominator is 0. If the denominator is 0, the statements after this statement in the try block are skipped. The catch block catches
the thrown exception as its parameter and executes the statements inside it.
Output
ArithmeticException => / by zero
17. Multiple catch Blocks
We can use multiple catch statements for different kinds of exceptions that can occur from a single block of code in the try block.
Syntax
try {
// code to check exceptions
catch (exception1) {
// code to handle the exception
catch (exception2) {
// code to handle the exception
}
catch (exception n) {
// code to handle the exception
Example
public class MultipleCatchBlock {
public static void main(String[] args) {
try {
int x[] = new int[5];
x[5] = 40 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
System.out.println("The program ends here");
Run Code >>
Here, our program matches the type of exception that occurred in the try block with the catch statements. If the exception that
occurred matches any of the usual catch statements, that particular catch block gets executed.
Output
Arithmetic Exception occurs
The program ends here
4. throw
The throw keyword is used to explicitly throw a checked or an unchecked exception.
The exception that is thrown needs to be of type Throwable or a subclass of Throwable.
We can also define our own set of conditions for which we can throw an exception explicitly using the throw keyword.
The program's execution flow stops immediately after the throw statement is executed, and the nearest try block is
checked to see if it has a catch statement that matches the type of exception.
Syntax
throw new exception_class("error message");
Example of Exception Handling using Java throw
class ThrowExample {
// Method to check if a number is negative
public static void checkNumber(int number) {
if (number < 0) {
// Throwing an IllegalArgumentException if the number is negative
throw new IllegalArgumentException("Number cannot be negative");
} else {
System.out.println("Number is " + number);
public static void main(String[] args) {
try {
// Trying to check a negative number
checkNumber(-5);
} catch (IllegalArgumentException e) {
// Handling the thrown exception
System.out.println("Caught an exception: " + e.getMessage());
5. throws
The throws keyword is used in the method signature to indicate that a method in Java can throw particular exceptions. This
notifies the method that it must manage or propagate these exceptions to the caller.
import java.io.IOException;
public class ThrowsExample {
public static void main(String[] args) {
try {
methodWithException();
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
public static void methodWithException() throws IOException {
// Simulate an IOException
throw new IOException("This is an IOExce