Exception Handling
Written and reviewed by Gagan Bhardwaj · Senior IT Faculty · 15+ years’ experience
What is Exception Handling?
An exception is an unexpected event that occurs during program execution and disrupts the normal flow — for example dividing by zero, accessing an array out of bounds, or opening a missing file. Exception handling lets your program deal with such errors gracefully instead of crashing.
The Five Keywords
| Keyword | Use |
|---|---|
try | Wraps the risky code. |
catch | Handles the exception if one occurs. |
finally | Always runs (cleanup), whether or not an exception occurred. |
throw | Manually throws an exception. |
throws | Declares that a method might throw an exception. |
Example
public class Main { public static void main(String[] a) { try { int x = 10 / 0; // risky } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Done"); // always runs } } }
Cannot divide by zero Done
Checked vs Unchecked Exceptions
| Type | Checked at | Examples |
|---|---|---|
| Checked | Compile time (must handle) | IOException, SQLException |
| Unchecked | Runtime | ArithmeticException, NullPointerException, ArrayIndexOutOfBounds |
Without handling, one error crashes the whole program. With handling, you show a friendly message and keep running — essential for real apps.
Never leave an empty catch {} block — it hides bugs. At least log the error.
Summary
- Exceptions disrupt normal flow; handling prevents crashes.
- Keywords: try, catch, finally, throw, throws.
finallyalways runs; checked exceptions must be handled, unchecked occur at runtime.
Exception Handling क्या है?
Exception program चलते समय होने वाली एक अनचाही घटना है जो सामान्य flow को रोक देती है — जैसे zero से भाग देना, array की सीमा से बाहर जाना, या गायब file खोलना। Exception handling ऐसी errors को crash हुए बिना संभालने देता है।
पाँच Keywords
| Keyword | उपयोग |
|---|---|
try | जोखिम भरे code को लपेटता है। |
catch | exception होने पर संभालता है। |
finally | हमेशा चलता है (cleanup)। |
throw | manually exception फेंकता है। |
throws | बताता है कि method exception फेंक सकता है। |
उदाहरण
try { int x = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Done"); }
Cannot divide by zero Done
Checked vs Unchecked
| प्रकार | कब check | उदाहरण |
|---|---|---|
| Checked | Compile time (संभालना ज़रूरी) | IOException, SQLException |
| Unchecked | Runtime | ArithmeticException, NullPointerException |
बिना handling के एक error पूरा program crash कर देती है। handling से friendly message दिखाकर program चलता रहता है।
खाली catch {} block कभी न छोड़ें — यह bugs छुपाता है। कम से कम error log करें।
सारांश
- Exceptions normal flow रोकती हैं; handling crash रोकती है।
- Keywords: try, catch, finally, throw, throws।
finallyहमेशा चलता है; checked ज़रूरी, unchecked runtime पर।