Skip to main content
Lesson 17 - Exceptions
ZIPPDF (letter)
Lesson MenuPreviousNext
  
Exception Messages page 5 of 8

  1. If a program does not handle exceptions at all, it will crash and produce a message that describes the exception and where it happened. This information can be used to help track down the cause of a problem.

  2. The program shown below throws an ArithmeticException when the program tries to divide by zero. The program crashes and prints out information about the exception:

    public class DivideByZero
    {
      public static void main (String[] args)
      {
        int numerator = 23;
        int denominator = 0;
    
        // the following line produces an AritmeticException
        System.out.println(numerator/denominator);
    
        System.out.println("This text will not print");
      }
    }
    
    Run Output:
    
    Exception in thread "main" java.lang.ArithmeticException: / by zero
            at DivideByZero.main(DivideByZero.java:10)

    The first line of the output tells which exception was thrown and gives some information about why it was thrown.

    The rest of the output tells where the exception occurred and is referred to as a call stack trace. In this case, there is only one line in the call stack trace, but there could be several, depending on where the exception originated. The trace line gives the method, file, and line number where the exception happened.

  3. When exceptions are handled by a program, it is possible to obtain information about an exception by referring to the "exception object" that Java creates in response to an exception condition. Every exception object contains a String that can be accessed using the getMessage method as follows:

    try
    {
      quotient = numerator/denominator;
      System.out.println("The answer is: " + quotient);
    }
    catch (ArithmeticException e)
    {
      System.out.println(e.getMessage);
    }
    

    If the exception is thrown, the following message is displayed

    / by zero
  4. Printing the value returned by getMessage can be useful in situations where we are unsure of the type of error or its cause.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.