Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 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

KeywordUse
tryWraps the risky code.
catchHandles the exception if one occurs.
finallyAlways runs (cleanup), whether or not an exception occurred.
throwManually throws an exception.
throwsDeclares 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

TypeChecked atExamples
CheckedCompile time (must handle)IOException, SQLException
UncheckedRuntimeArithmeticException, 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.
  • finally always runs; checked exceptions must be handled, unchecked occur at runtime.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 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.
Next topicCollections (ArrayList, HashMap) Your progress: 23 / 61 (38%) · Lesson 24 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free