DEV Community

Cover image for Java Exception Handling Made Easy for Beginners?
Arul .A
Arul .A

Posted on

Java Exception Handling Made Easy for Beginners?

What is Exception Handling?
Exception handling in Java is a mechanism to handle runtime errors so that the program doesnโ€™t crash and can continue executing smoothly.

Why Exception Handling is Needed?
If you ignore exceptions, your program will:
1.Crash suddenly
2.Show ugly error messages
3.Lose user trust
With exception handling, you can:
1.Prevent crashes
2.Show meaningful messages
3.Maintain program flow

Example Without Exception Handling:

public class Test {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        int result = a / b;  // Runtime error
        System.out.println(result);
    }
}

Enter fullscreen mode Exit fullscreen mode

Output:
Exception in thread "main" java.lang.ArithmeticException

Example With Exception Handling:

public class Test {
    public static void main(String[] args) {
        try {
            int a = 10;
            int b = 0;
            int result = a / b;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
        System.out.println("Program continues...");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output :
Cannot divide by zero
Program continues...

Important Keywords in Exception Handling:

  1. try Contains code that may cause an exception
  2. catch Handles the exception
  3. finally Always executes (whether exception occurs or not).
try {
    // risky code
} catch (Exception e) {
    // handling code
} finally {
    // always runs
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)