DEV Community

Cover image for Exception Handling in Java
Kavitha
Kavitha

Posted on

Exception Handling in Java

Introduction:

  • Exception handling is a mechanism to handle the run time exception.
  • An exception is an unexpected event that occurs during the execution of a program and disrupts its normal flow.
  • Java provides a robust framework to handle such errors gracefully without crashing the program.

Exception :

  • An exception is an abnormal condition that occurs at runtime, such as: Dividing a number by zero
  • Accessing an invalid array index
  • Trying to open a file that does not existException is a unexpected event, that distrub the normal flow of the program.

Example:

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

Types of Exceptions in Java
1.Checked exception
2.Unchecked exception

Checked exception :
1.Checked exception is also know compile time exception.
2.JDK will detect the compile time exception.We should fixed the exception before run the program.
Examples:

  • IOException
  • SQLException

Unchecked Exception :
1.Unchecked exception is aslo know as run time exception
Examples:

  • ArithmeticException
  • NullPointerException

Exception Handling Keywords in Java

  1. try -Used to write code that may cause an exception.
try {
    int x = 10 / 0;
}
Enter fullscreen mode Exit fullscreen mode

2. catch
-Used to handle the exception.

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

3. finally
-Always executes whether an exception occurs or not.

finally {
    System.out.println("Program ended");
}
Enter fullscreen mode Exit fullscreen mode

-Throwable is a class. Exception and Error is a subclass of Throwable.

Error:
-Serious problems that cannot be handled by programs
Examples:

  • OutOfMemoryError
  • StackOverflowError

Example Program

class ExceptionDemo {
    public static void main(String[] args) {
        try {
            int a = 20 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Exception caught");
        } finally {
            System.out.println("Execution completed");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Exception caught
Execution completed
Enter fullscreen mode Exit fullscreen mode

Top comments (0)