An exception is an event that disrupts the normal flow of a program: dividing by zero, a missing file, invalid input, a null reference. Without handling, the JVM prints a stack trace and stops the program. Exception handling lets you recover gracefully.
try and catch#
100 / 10 = 10 Cannot divide by 0: / by zero 100 / 5 = 20 Program continues normally
When an exception is thrown inside try, the rest of the try block is skipped and control jumps to the matching catch.
Exception यानी program चलते समय आई कोई गड़बड़ (zero से भाग, गलत index, file न मिलना)। जिस code में गड़बड़ हो सकती है उसे try में रखें, और catch में बताएँ कि गड़बड़ होने पर क्या करना है। इससे program बीच में crash नहीं होता।
Multiple catch blocks, multi-catch and finally#
arr[1] / n = 4 (finally always runs) Not a number: x (finally always runs) Problem: ArrayIndexOutOfBoundsException (finally always runs) Problem: ArithmeticException (finally always runs)
The exception hierarchy: checked vs unchecked#
Throwable
├── Error (serious JVM problems: OutOfMemoryError - don't catch)
└── Exception
├── IOException, SQLException, ... ← CHECKED: must catch or declare
└── RuntimeException ← UNCHECKED: usually programming bugs
├── ArithmeticException
├── NullPointerException
├── ArrayIndexOutOfBoundsException
├── NumberFormatException
└── IllegalArgumentException
- Checked exceptions - the compiler forces you to either
catchthem or declare them withthrows. They represent problems outside your control (files, network, database). - Unchecked exceptions (
RuntimeExceptionand children) - not enforced; they usually mean a bug to fix (null references, bad indexes).
NullPointerException - name was never assigned ClassCastException - a String is not an Integer
throw and throws#
Use throw to raise an exception yourself - typically to reject invalid arguments. Use throws in a method signature to declare checked exceptions the caller must handle:
OK, balance 3800.0 Rejected: Amount must be positive Rejected: Insufficient funds: balance 3800.0 Loaded app.cfg Config error: app.txt not found
Custom exceptions#
Create your own exception classes for business rules. Extend Exception for checked, RuntimeException for unchecked:
Riya admitted Not admitted: Marks 54 are below the cut-off of 60 (short by 6)
try-with-resources#
Resources such as files, scanners and database connections must be closed. try (...) closes them automatically, even if an exception occurs:
> Lesson 1: Basics > Lesson 2: OOP missing.txt does not exist
Good practice: catch the most specific exception you can handle, never swallow exceptions with an empty catch {}, include helpful messages, and don't use exceptions for normal control flow (check hasNextInt() instead of catching every bad input when you can).
Summary#
trythe risky code,catchspecific exceptions, usefinally(or try-with-resources) for clean-up.- Checked exceptions must be caught or declared with
throws; unchecked ones (RuntimeException) are usually bugs. throw new X("message")raises an exception; create custom exceptions by extendingExceptionorRuntimeException.