In Java, any problem that prevents the program from running smoothly is an Throwable object. However, not all problems are created equal. Some are fatal system failures (Errors) that you cannot fix, while others are logical "hiccups" (Exceptions) that your code can catch and resolve. Learning to handle these effectively is known as Exception Handling.
In Java, every error and exception is a subclass of the java.lang.Throwable class. This hierarchy is split into two main branches:
Serious problems that a reasonable application should not try to catch. These are usually related to the environment (JVM) or hardware.
Example: OutOfMemoryError, StackOverflowError.
Conditions that an application might want to catch. These are caused by the program's logic or external inputs.
Example: NullPointerException, IOException.
Exceptions are further divided into two categories based on when the compiler notices them:
The compiler forces you to handle these. If you don't handle them using a try-catch or the throws keyword, the code won't even compile. They usually occur due to external factors like files or databases.
IOExceptionSQLExceptionClassNotFoundExceptionThese occur during the execution of the program. They are usually the result of bad programming logic. The compiler doesn't force you to check these, but they will crash your app if they happen.
ArithmeticException (e.g., dividing by zero)NullPointerException (accessing a null object)ArrayIndexOutOfBoundsExceptionTo prevent your program from stopping abruptly, Java provides a structured way to handle exceptions.
This example shows how to catch a specific exception and use the finally block for cleanup.
Sometimes, Java’s built-in exceptions aren't enough. You can create your own by extending the Exception class. This is common in business logic, like throwing an InsufficientFundsException in a banking app.
class AgeException extends Exception { ... }
While you catch exceptions, you usually just watch Errors happen. Here are the big ones:
FileNotFoundException instead of a generic Exception.finally (or try-with-resources) to close connections.Q: Can we have a try block without a catch block?
A: Yes, but only if you have a finally block. A try-finally is valid for cleanup, but it won't handle the exception.
Q: What is the difference between throw and throws?
A: throw is used to trigger an exception manually. throws is used in method signatures to declare which exceptions might be thrown.
Q: What is "Try-with-resources"?
A: Introduced in Java 7, it's a way to automatically close resources (like files) without needing a manual finally block.
Errors and Exceptions are the safety nets of your code. By mastering the hierarchy and the try-catch-finally mechanism, you ensure that your application doesn't just crash, but fails gracefully—providing a better experience for the user and easier debugging for you.