Java - Exception Exception Handling

What Is an Exception?

An exception is a condition that may arise during a normal execution.

For example, attempts to divide an integer by zero.


int x = 10, y = 0, z;
z = x/y; // Divide-by-zero

Syntax

The code that handles the exception is known as an exception handler.

The exception handing code is as follows:

try {
        // your code
}
catch(Exception1 e1){
        // Handle exception1 here
}
catch(Exception2 e2){
        // Handle exception2 here
}
catch(Exception3 e3){
        // Handle exception3 here
}
catch(Exception4 e4){
        // Handle exception4 here
}

try-catch Block

A try and catch block looks like the following:

try {
  // Code for the try block goes here
}
catch (ExceptionClassName parameterName) {
        // Exception handling code goes here
}

To associate one or more catch blocks to a try block.

try {
        // Your code that may throw an exception goes here
}
catch (ExceptionClass1 e1){
        // Handle exception of ExceptionClass1 type
}
catch (ExceptionClass2 e2){
        // Handle exception of ExceptionClass2 type
}
catch (ExceptionClass3 e3){
        // Handle exception of ExceptionClass3 type
}

Handling an Exception Using a try-catch Block

Demo

public class Main {
  public static void main(String[] args) {
    int x = 10, y = 0, z;
    try {//from   ww  w.  ja  v  a 2s  .  c o  m
      z = x / y;
      System.out.println("z = " + z);
    } catch (ArithmeticException e) {
      // Get the description of the exception
      String msg = e.getMessage();

      // Print a custom error message
      System.out.println("An error has occurred. The error is: " + msg);
    }

    System.out.println("At the end of the program.");
  }
}

Result

Related Topics