Exception Handling
What Are Exceptions?
Imagine you're following a recipe and it says "add 2 eggs." But the carton is empty. You can either panic and burn down the kitchen (crash), or handle it gracefully — maybe skip the eggs or run to the store. That's what exception handling does for your code.
An exception is Java's way of saying "something unexpected happened." When one is thrown, Java unwinds the call stack looking for a handler. Without handling, your program crashes with a scary red error message. With proper handling, you catch the problem and deal with it.
Java has two main categories:
- Checked exceptions — Java forces you to handle these (like
IOException). The compiler won't let your code run without a try/catch or throws declaration. - Unchecked exceptions — runtime problems Java doesn't force you to handle (like
NullPointerException,ArrayIndexOutOfBoundsException). These are usually bugs in your code.
Try / Catch / Finally
Throwing Exceptions & Custom Exceptions
Sometimes you want to be the one throwing an exception. Maybe someone passes a negative age to your method — that doesn't make sense, so you throw an exception to signal the problem.
Use throw new ExceptionType("message") to throw an exception. Use throws in the method signature to warn callers that this method might throw a checked exception.
You can also create your own custom exception classes by extending Exception (checked) or RuntimeException (unchecked).
Throw, Throws & Custom Exceptions
Try-With-Resources
catch (Exception e) is like a doctor saying "you're sick" without telling you what's wrong. Catch NumberFormatException, IOException, etc. so you can handle each problem appropriately. Use generic Exception only as a last-resort safety net.Quick check
Continue reading