🔴 Advanced · Lesson 23
Exception Handling in Java
In this lesson: Handle errors in Java with try, catch, finally, throw and throws — checked vs unchecked with examples. In Hindi & English.
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
Java
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 } } }
▶ Output
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 |
💡 Why handle exceptions?
Without handling, one error crashes the whole program. With handling, you show a friendly message and keep running — essential for real apps.
⚠️ Common mistake
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.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
