Object Oriented Programming with Java

⌘K
  1. Home
  2. Docs
  3. Object Oriented Programmi...
  4. Exception Handling
  5. Java’s Built-in Exceptions

Java’s Built-in Exceptions

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:

  1. Exception
  2. Error
             Throwable
             /       \
        Exception    Error

1. 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 TypeDescription
IOExceptionOccurs during input/output operations.
FileNotFoundExceptionThrown when a file cannot be found.
SQLExceptionRelated to database access errors.
ClassNotFoundExceptionRaised when a class cannot be located.
InterruptedExceptionOccurs 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 TypeDescription
ArithmeticExceptionDivision by zero or mathematical error.
NullPointerExceptionAccessing an object that is null.
ArrayIndexOutOfBoundsExceptionAccessing array elements out of range.
NumberFormatExceptionInvalid conversion from string to number.
IllegalArgumentExceptionInvalid 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 TypeDescription
OutOfMemoryErrorThrown when JVM runs out of memory.
StackOverflowErrorCaused by excessive recursion.
VirtualMachineErrorIndicates problems in JVM execution.
AssertionErrorThrown 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

FeatureChecked ExceptionsUnchecked Exceptions
Compile-time CheckYesNo
Handled using try-catch?RequiredOptional
ExamplesIOException, SQLExceptionNullPointerException, ArithmeticException
Occurs due toExternal factorsProgramming logic errors

Best Practices for Handling Built-in Exceptions

  1. Catch specific exceptions instead of generic ones like Exception.
  2. Avoid empty catch blocks — always log or respond to the error.
  3. Use finally or try-with-resources to close resources safely.
  4. Don’t overuse try-catch — handle exceptions where they can be recovered.
  5. 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.

Tags , , , , , , , ,

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *