Learn about Java’s built-in exceptions with examples and hierarchy. Understand checked and unchecked exceptions, their types, and how to handle them effectively in modern Java development.
Introduction
In Java programming, exceptions are an integral part of writing robust, error-free applications. Errors can occur for various reasons — invalid inputs, missing files, or unexpected system behavior. To manage these situations gracefully, Java provides a rich set of built-in exceptions that help developers handle runtime anomalies without crashing the application.
In this comprehensive guide, we’ll explore Java’s built-in exceptions, their hierarchy, types, and real-world examples. You’ll also learn best practices for using these exceptions effectively to write reliable, maintainable, and efficient Java code.
What Are Built-in Exceptions in Java?
Built-in exceptions are predefined classes in Java that represent common runtime and compile-time errors. These exceptions are part of the java.lang package, which means they are automatically available to every Java program.
Instead of writing custom error classes for every issue, Java developers can use these pre-defined exceptions to handle common problems like invalid data, file handling errors, division by zero, and more.
Example:
public class Example {
public static void main(String[] args) {
try {
int result = 10 / 0; // Causes ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed!");
}
}
}In this example, the ArithmeticException (a built-in exception) is used to catch division errors at runtime.
Hierarchy of Java Exceptions
All exceptions in Java inherit from the java.lang.Throwable class. This class has two main subclasses:
- Exception
- Error
Throwable
/ \
Exception Error1. Exception Class
Represents conditions that a program should catch and handle.
It is further divided into:
- Checked Exceptions
- Unchecked Exceptions (Runtime Exceptions)
2. Error Class
Represents serious system-level problems that a program should not attempt to handle, such as memory leaks or JVM crashes.
Types of Built-in Exceptions in Java
Java’s built-in exceptions are primarily categorized into two main types:
1. Checked Exceptions
Checked exceptions are verified by the compiler at compile-time.
If a method might throw a checked exception, it must either handle it using try-catch or declare it using the throws keyword.
Common Checked Exceptions:
| Exception Type | Description |
|---|---|
| IOException | Occurs during input/output operations. |
| FileNotFoundException | Thrown when a file cannot be found. |
| SQLException | Related to database access errors. |
| ClassNotFoundException | Raised when a class cannot be located. |
| InterruptedException | Occurs when a thread is interrupted. |
Example:
import java.io.*;
public class CheckedExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("data.txt");
file.read();
} catch (IOException e) {
System.out.println("File operation failed: " + e.getMessage());
}
}
}Here, the IOException must be handled using a try-catch block because it is a checked exception.
2. Unchecked Exceptions (Runtime Exceptions)
Unchecked exceptions are not checked at compile time.
They occur due to logical programming errors, such as invalid casting, array index out of bounds, or null references.
Common Unchecked Exceptions:
| Exception Type | Description |
|---|---|
| ArithmeticException | Division by zero or mathematical error. |
| NullPointerException | Accessing an object that is null. |
| ArrayIndexOutOfBoundsException | Accessing array elements out of range. |
| NumberFormatException | Invalid conversion from string to number. |
| IllegalArgumentException | Invalid argument passed to a method. |
Example:
public class UncheckedExample {
public static void main(String[] args) {
String value = null;
System.out.println(value.length()); // Throws NullPointerException
}
}3. The Error Class
Errors indicate serious problems that occur beyond the control of the application, such as hardware failure or memory exhaustion. These are typically not handled using try-catch because they represent issues the application cannot recover from.
Common Errors:
| Error Type | Description |
|---|---|
| OutOfMemoryError | Thrown when JVM runs out of memory. |
| StackOverflowError | Caused by excessive recursion. |
| VirtualMachineError | Indicates problems in JVM execution. |
| AssertionError | Thrown when an assertion fails. |
Example:
public class ErrorExample {
public static void recursiveMethod() {
recursiveMethod(); // infinite recursion
}
public static void main(String[] args) {
recursiveMethod(); // Causes StackOverflowError
}
}Difference Between Checked and Unchecked Exceptions
| Feature | Checked Exceptions | Unchecked Exceptions |
|---|---|---|
| Compile-time Check | Yes | No |
| Handled using try-catch? | Required | Optional |
| Examples | IOException, SQLException | NullPointerException, ArithmeticException |
| Occurs due to | External factors | Programming logic errors |
Best Practices for Handling Built-in Exceptions
- Catch specific exceptions instead of generic ones like
Exception. - Avoid empty catch blocks — always log or respond to the error.
- Use finally or try-with-resources to close resources safely.
- Don’t overuse try-catch — handle exceptions where they can be recovered.
- Use custom exceptions when built-in ones don’t represent your error scenario.
Real-world Use Case Example
import java.io.*;
public class FileHandler {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("students.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("Error: File not found.");
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}Here, multiple built-in exceptions (FileNotFoundException, IOException) are handled gracefully, ensuring the program remains stable and user-friendly.
Conclusion
Java’s built-in exceptions are the foundation of effective error handling. Understanding these exceptions helps you write cleaner, more resilient, and maintainable programs.
From checked exceptions like IOException to runtime exceptions like NullPointerException, mastering these concepts enables you to anticipate potential issues and prevent program crashes.
By combining proper exception handling with clear logging and meaningful error messages, you can elevate the reliability and professionalism of your Java applications.
Frequently Asked Questions (FAQs)
1. What are built-in exceptions in Java?
Built-in exceptions are predefined classes in Java used to handle common runtime and compile-time errors, such as IOException and ArithmeticException.
2. What is the difference between checked and unchecked exceptions?
Checked exceptions are verified at compile time, while unchecked exceptions occur at runtime and are not checked by the compiler.
3. Can we handle Error types in Java?
Although possible, handling Error types is not recommended since they represent serious system-level problems.
4. What is the parent class of all exceptions?
The Throwable class is the parent of all exceptions and errors in Java.
5. Why should we use built-in exceptions?
They save time, improve reliability, and promote standardized error handling across Java applications.
