DEV Community

Cover image for Exception Handling in Java
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Exception Handling in Java

Exception
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

Exception Handling
Exception handling in Java is a mechanism used to handle exceptional conditions that occur during program execution. It helps prevent the program from terminating unexpectedly and allows developers to provide appropriate recovery or error-handling logic.

  • Separates error-handling code from normal program logic.
  • Helps maintain the normal flow of program execution.
  • Supports handling of both checked and unchecked exceptions.

Types of Exception
1. Built-in Exception
Built-in Exception are pre-defined exception classes provided by Java to handle common errors during program execution. There are two type of built-in exception in java.

  • Checked Exception: These exceptions are checked at compile time, forcing the programmer to handle them explicitly.
  • Unchecked Exception: These exceptions are checked at runtime and do not require explicit handling at compile time.

2. User-Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called "user-defined Exceptions".

  • The try block contains code that might throw an exception,
  • The catch block handles the exception if it occurs.
class ExceptionDemo{
    public static void main(String[] args) {

        int n = 10;
        int m = 0;

        try {
            int ans = n / m;
            System.out.println("Answer: " + ans);
        } catch (ArithmeticException e){
            System.out.println("Error: Division by 0!");
        } 
    }
}
//Error: Division by 0!
Enter fullscreen mode Exit fullscreen mode

throw and throws Keywords

  • The throw keyword is used to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
  • The throws keyword indicates what exception type may be thrown by a method.There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
public class Main {
  static void checkAge(int age) { 
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old."); 
    } else {
      System.out.println("Access granted - You are old enough!"); 
    }
 } 

 public static void main(String[] args) { 
   checkAge(15); 
 } 
}
//Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
    at Main.checkAge(Main.java:4)
    at Main.main(Main.java:11)
Enter fullscreen mode Exit fullscreen mode
  checkAge(22); 
//Access granted - You are old enough!
Enter fullscreen mode Exit fullscreen mode

throws

public class Main {
  static void checkAge(int age) throws ArithmeticException { 
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old."); 
    } else {
      System.out.println("Access granted - You are old enough!"); 
    }
 } 

 public static void main(String[] args) { 
   checkAge(15); 
 } 
}
Enter fullscreen mode Exit fullscreen mode

finallly
The finally keyword is used to execute code (used with exceptions - try..catch statements) no matter if there is an exception or not.

public class Main {
  public static void main(String[] args) {
    try {
      int[] myNumbers = {1, 2, 3};
      System.out.println(myNumbers[10]);
    } catch (Exception e) {
      System.out.println("Something went wrong.");
    } finally {
      System.out.println("The 'try catch' is finished.");
    }
  }
}
//Something went wrong.
The 'try catch' is finished.
Enter fullscreen mode Exit fullscreen mode

References
https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
https://www.geeksforgeeks.org/java/throw-throws-java/
https://www.w3schools.com/java/ref_keyword_finally.asp
https://www.geeksforgeeks.org/java/exceptions-in-java/

Top comments (0)