Exception handling in Java

Key takeaways:

  • Exceptions are errors that disrupt a program’s normal flow, like dividing by zero or invalid inputs.

  • Java has two types of exceptions:

    • Checked exceptions (checked at compile-time)

    • Unchecked exceptions (occur at runtime)

  • Use a try-catch block to manage exceptions: the try block contains code that might throw an error, while the catch block addresses and handles the error.

  • The finally block runs code no matter what—whether an exception occurs or not.

  • Use the throw keyword to manually throw an exception when a specific condition occurs (e.g., invalid input).

  • Proper exception handling makes Java programs robust, preventing crashes and ensuring smooth execution.

Exception handling is an essential feature in Java that enables developers to manage runtime errors efficiently, ensuring applications run smoothly. It is a mechanism that detects and manages unexpected or erroneous conditions, preventing abrupt program termination. In this article, we will explore the types of exceptions, the exception hierarchy, and how to handle exceptions in Java with best practices.

What is an exception?

An exception is an event that arises during program execution, interrupting its normal flow. Exceptions arise due to invalid inputs, hardware failures, or programming errors. Java provides a robust exception handling mechanism to manage these issues gracefully.

For example, dividing a number by zero or accessing an invalid array index can trigger an exception.

Exception hierarchy in Java

Exception handling in Java enables us to manage errors occurring while the program runs. When an exception occurs, the Java virtual machine (JVM)This is a Java platform, which is responsible for executing Java bytecode and providing various runtime services. throws it, and our code can catch and handle it.

There are two types of exceptions in Java:

  • Checked exceptions: At compile-time, these exceptions are validated. If a method’s code segment throws a checked exception, it must handle or declare it explicitly using the throws keyword.

  • Unchecked exceptions: Unlike checked exceptions, these exceptions do not require explicit handling or declaration. They can occur at runtime and are not enforced by the compiler.

Examples of checked and unchecked exceptions in Java
Examples of checked and unchecked exceptions in Java

Exception handling keywords in Java

Java provides several keywords to handle exceptions effectively:

The try-catch block

The try-catch statement in Java handles exceptions. The try block contains the code to be executed, while the catch block defines the actions to take if an exception occurs.

public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// Code that may throw an exception
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Exception handling code
System.out.println("An error occurred: " + e.getMessage());
}
}
// Method that performs division
public static int divide(int numerator, int denominator) {
return numerator / denominator;
}
}
Explanation:
  • Lines 1–2: The code starts with declaring a public class ExceptionHandlingExample and its main method.

  • Line 3: The try block includes the code that could throw an exception.

  • Line 5: Inside the try block, a division operation is attempted by calling the divide() method with arguments 10 and 0.

  • Lines 7–10: The catch block starts, specifying that it will catch ArithmeticException if it occurs within the try block.

  • Lines 14–16: The divide() method is declared, which takes two integer parameters: numerator and denominator. Inside the method, the division operation numerator / denominator is performed, and the result is returned as the method’s output.

The finally block

The finally block in Java is optional and executes code regardless of whether an exception is thrown. It guarantees the execution of specific code even if an exception occurs.

public class Finally{
public static void main(String[] args) {
int result = divideNumbers(10, 0);
System.out.println("Result: " + result);
}
public static int divideNumbers(int dividend, int divisor) {
try {
return dividend / divisor;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
return 0;
} finally {
System.out.println("Finally block executed.");
}
}
}
Explanation:
  • Line 1: The code begins with declaring a public class named Finally.

  • Lines 2–4: The code attempts to perform a division operation by calling the divideNumbers method with arguments 10 and 0.

  • Line 7: The divideNumbers method is declared, which takes two integer parameters—dividend and divisor.

  • Lines 8–9: The try block contains the division operation dividend / divisor.

  • Lines 10–15: If an ArithmeticException is caught, the code within the catch block is executed. It prints an error message to the console using the System.out.println statement. The error message prints out the message obtained from the caught exception, e.getMessage(). It then returns 0.

The throw keyword

The throw keyword in Java is used to explicitly raise an exception. When executed, it disrupts the program’s normal flow, passes control to the nearest matching catch block, or terminates the program if no handler is found.

public class Throw {
public static void main(String[] args) {
try {
validateAge(15);
} catch (IllegalArgumentException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
public static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18");
}
// Additional code if age is valid
System.out.println("Age is valid.");
}
}
Explanation:
  • Line 1: The program starts with declaring a public class named Throw.

  • Lines 3–9: The main method is the program’s entry point.

  • Line 4: The code calls the validateAge method with the argument 15.

  • Lines 57: It specifies that it will catch IllegalArgumentException within the try block.

  • Line 10: The validateAge method is declared, which takes an integer parameter age. Inside the method, the if condition to check if age is less than 18.

  • Line 12: If the age is under 18, the code throws a new IllegalArgumentException.

  • Line 15: If the age is valid (i.e., not less than 18), the code after the if condition is executed. In this case, it prints "Age is valid." to the console.

Conclusion

In conclusion, exception handling in Java is a powerful tool that allows developers to manage errors gracefully, ensuring programs run smoothly and reliably. Using keywords like try-catch, finally, and throw, developers can effectively handle unexpected situations, improve code stability, and provide better user experiences. Proper exception handling is essential for building robust and maintainable Java applications.

Note: For a more detailed coverage of exception handling in Java, look at the short course, Java Exception Handling Made Simple.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What are the five keywords of exception handling in Java?

The five keywords are:

  1. try: Defines a block to test for exceptions.
  2. catch: Handles exceptions thrown in the try block.
  3. finally: Executes code regardless of exception occurrence.
  4. throw: Used to manually throw an exception.
  5. throws: Declares exceptions a method can throw.

How does @ExceptionHandler work?

@ExceptionHandler is a Spring annotation used in controller classes to handle specific exceptions. When an exception occurs, the method annotated with @ExceptionHandler processes the exception and provides a custom response instead of letting it propagate.

Look at Exception handling in Spring Boot for more details.


What is the difference between final and finally?

  • final: It’s a keyword used to declare constants, prevent method overriding, or inheritance of a class.
  • finally: It’s a block that executes code after a try-catch, regardless of whether an exception occurs.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved