Java Exception Handling – Complete Guide with Examples
Learn Java exception handling, how to handle runtime and compile-time errors using try, catch, finally, throw, and throws keywords, and create custom exceptions for robust Java applications.
Exception Handling in Java – Complete Detailed Tutorial
Exception Handling is a mechanism in Java to handle runtime errors gracefully, without terminating the program abruptly.
- Exception: An event that occurs during program execution that disrupts normal flow.
- Error: Serious problems that cannot be handled by programs (like
OutOfMemoryError). - Exception Classes: All exceptions are subclasses of
java.lang.Exception.
1. Types of Exceptions
- Checked Exceptions:
- Occur at compile-time
- Must be handled using try-catch or throws
- Example:
IOException,SQLException - Unchecked Exceptions (Runtime Exceptions):
- Occur at runtime
- Optional to handle
- Example:
ArithmeticException,NullPointerException
2. try, catch, and finally
try: Block of code that may throw an exception.
catch: Block to handle the exception.
finally: Block that executes always, used for cleanup.
Example:
Output:
3. throw Keyword
- Used to explicitly throw an exception in the program.
- Can throw checked or unchecked exceptions
Example:
Output:
4. throws Keyword
- Declares that a method may throw an exception
- Handled by the caller of the method
Example:
Output:
5. Custom Exceptions
- You can create your own exception class by extending
ExceptionorRuntimeException.
Example:
Output:
6. Key Points
- Use try-catch for handling exceptions
- finally block executes always
- throw is used to explicitly throw an exception
- throws declares possible exceptions for a method
- Custom exceptions help in business logic validation