DEV Community

Jayashree
Jayashree

Posted on

What is Throwable in Java? A Complete Guide

When learning Java, one of the most important topics is Exception Handling. At the core of this concept lies the Throwable class.

In this blog, we’ll break down what Throwable is, its hierarchy, and how it works in a simple and clear way.

What is Throwable?

  • In Java, Throwable is the root class of all errors and exceptions.
  • In simple terms, anything that can be thrown using the throw keyword must be a subclass of Throwable.

1. Error (Serious Problems)

Error represents serious issues at the JVM level.

These are usually not recoverable and should not be handled in normal applications.

Examples:

  • OutOfMemoryError
  • StackOverflowError

Note: Catching Errors is generally not recommended.

2. Exception (Recoverable Issues)

Exception represents problems that can occur in your program and can be handled.

Types of Exceptions:

1.Checked Exceptions

  • Checked at compile-time
  • Must be handled using try-catch or throws

Examples:

  • IOException
  • SQLException

2.Unchecked Exceptions (Runtime Exceptions)
Occur at runtime
Handling is optional

Examples:

  • NullPointerException
  • ArithmeticException

Example Code

public class Test {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (Exception e) {
            System.out.println("Error occurred: " + e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

throw vs throws
throw

Used to explicitly throw an exception

throw new IllegalArgumentException("Invalid value");
Enter fullscreen mode Exit fullscreen mode

throws

Used in method declarations to specify exceptions

public void readFile() throws IOException {
}
Enter fullscreen mode Exit fullscreen mode

Real-Life Analogy

Think of an application:

System crash → Error
Invalid user input → Exception

Conclusion
Throwable→ Root class
Error → Serious, unrecoverable issues
Exception → Recoverable issues
Exceptions → Checked and Unchecked

To become a strong Java developer, understanding Exception Handling is essential—and Throwable is the foundation of it.

Top comments (0)