DEV Community

Cover image for Exception Handling in Java
KIRUBAGARAN .K
KIRUBAGARAN .K

Posted on

Exception Handling in Java

Exception Handling in Java is a mechanism used to handle runtime errors so that the normal flow of the program can continue without crashing.

  • Handles abnormal conditions that occur during program execution.

  • Helps maintain program stability by preventing unexpected termination.

Basic try-catch
Basic Structure

try {
    // risky code
} catch (Exception e) {
    // handling code
} 
Enter fullscreen mode Exit fullscreen mode
  • The try block contains code that might throw an exception,

  • The catch block handles the exception if it occurs.

  • try → “Let me try this risky action”

  • catch → “Oops! I’ll handle the problem”

Handling Arithmetic Exception

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

Top comments (0)