Limited Offer
60% OFF on all plans!

Error / Exception Handling in Java

Handle errors gracefully with try/catch/finally, checked vs unchecked exceptions, multi-catch, try-with-resources, and creating custom exceptions.

Introduction to Exceptions

1. What is an Exception?

An exception is an event that disrupts normal program flow. In Java, exceptions are objects that extend `Throwable`. The two main branches are `Error` (JVM-level, unrecoverable) and `Exception` (application-level, recoverable).

Types of Exceptions

1. Checked Exceptions

Checked exceptions must be declared with `throws` or caught. They represent recoverable conditions like file not found or network failure.

2. Unchecked Exceptions (RuntimeException)

Unchecked exceptions extend `RuntimeException`. They do not need to be declared or caught — they represent programming mistakes.

3. Common Exception Types

A quick reference to the most common exceptions you will encounter in Java.

try / catch

1. Basic try-catch

Wrap risky code in `try`. If an exception is thrown, execution jumps to the matching `catch` block.

2. The Exception Object

The caught exception object has useful methods: `getMessage()`, `getClass().getSimpleName()`, and `printStackTrace()`.

3. Multi-catch

Catch multiple exception types with separate blocks, or combine them in one block using `|` (Java 7+).

finally Block

1. finally Execution

`finally` always runs — whether an exception was thrown or not. Commonly used for cleanup like closing connections.

Throwing Exceptions

1. throw new Exception

Use `throw` to raise an exception explicitly. Use `throws` in the method signature to declare checked exceptions.

Custom Exception Classes

1. Extending Exception

Extend `RuntimeException` for unchecked custom exceptions. Extend `Exception` for checked ones.

Error Propagation

1. Exception Bubbling

If a method does not catch an exception, it propagates up to the caller. This continues until it is caught or reaches `main` and crashes the program.

try-with-resources

1. Automatic Resource Closing

Any class implementing `AutoCloseable` can be used in a try-with-resources statement. The resource is automatically closed when the block exits — even if an exception is thrown.

2. Custom AutoCloseable

Implement `AutoCloseable` in your own classes to support try-with-resources.

Stack Trace & Call Stack

1. What is a Stack Trace?

A stack trace is the list of method calls that were active when the exception was thrown. It is printed from innermost (where the error happened) to outermost (where execution started).

2. Getting Stack Trace as String

Use `e.getStackTrace()` to get stack frames programmatically, or convert to a string for logging.