Handling an Exception Using a try-catch Block - Java Language Basics

Java examples for Language Basics:try catch finally

Description

Handling an Exception Using a try-catch Block

Demo Code

public class Main {
  public static void main(String[] args) {
    int x = 10, y = 0, z;
    try {/*w  w  w . j a  va 2  s.  co  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 Tutorials