DEV Community

Ajay Raja
Ajay Raja

Posted on

Exception Handling

Exception handling allows a program to deal with errors in a controlled way, ensuring smooth execution.


What is Exception Handling?

Exception handling is a technique used to handle runtime errors so that the program continues running instead of stopping suddenly.

In simple terms, it helps manage unexpected problems during program execution.

Types of Errors in Programming

Understanding errors is important before learning exception handling. There are three main types:

1. Compile-Time Errors

These errors occur during compilation due to syntax mistakes.

Example:

int a = 10
Enter fullscreen mode Exit fullscreen mode

2. Runtime Errors (Exceptions)

These occur while the program is running and can cause it to crash.

Example:

int a = 10 / 0;
Enter fullscreen mode Exit fullscreen mode

3. Logical Errors

These errors do not stop the program but produce incorrect output.

Example:

System.out.println(10 - 5); 
Enter fullscreen mode Exit fullscreen mode

What is an Exception?

An exception is an error that occurs during the execution of a program. When an exception happens, the normal flow of the program is interrupted.

Examples include:

  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException

Keywords Used in Exception Handling

try

The try block contains code that may cause an exception.

try {
    int a = 10 / 0;
}
Enter fullscreen mode Exit fullscreen mode

catch

The catch block handles the exception.

catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}
Enter fullscreen mode Exit fullscreen mode

finally

The finally block always executes, whether an exception occurs or not.

finally {
    System.out.println("Execution completed");
}
Enter fullscreen mode Exit fullscreen mode

Example Program

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

Importance of Exception Handling

  • Prevents program crashes
  • Maintains smooth program flow
  • Improves user experience
  • Helps in debugging

Top comments (0)