Skip to main content
Engineering LibreTexts

10.1: Handling Exceptional Conditions

  • Page ID
    15119
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

     /**
      * Precondition:  N > 0
      * Postcondition: avgFirstN() = (1+2+...+N)/N
      */
    public double avgFirstN(int N) {
        int sum = 0;
        for (int k = 1; k <= N; k++)
            sum += k;
        return sum/N;         // What if N is 0?
    } // avgFirstN()

    To introduce you to handling exceptional conditions, Figure [fig-intavg1] shows a method that computes the average of the first N integers, an admittedly contrived example. We use it mainly to illustrate the basic concepts involved in exception handling. As its precondition suggests, the avgFirstN() method expects that N will be greater than 0. If N happens to be 0, an error will occur in the expression sum/N, because you cannot divide an integer by 0.

    Traditional Error Handling

    Obviously, the method in Figure [fig-intavg1] should not simply ignore the possibility that N might be 0. Figure [fig-traditional] shows a revised version of the method, which includes code that takes action if the method’s precondition fails. Because there is no way to compute an average of 0 elements, the revised method decides to abort the program. Aborting the program appears to be a better alternative than returning 0 or some other default value (like \(-1\)) as the method’s result and thereby allowing an erroneous value to spread throughout the program. That would just compound the error.

     /**
      * Precondition:  N > 0
      * Postcondition: avgFirstN() equals (1+2+...+N) divided by N
      */
    public double avgFirstN(int N) {
        int sum = 0;
        if (N <= 0) {
          System.out.println(
               "ERROR avgFirstN: N <= 0. Program terminating.");
          System.exit(0);
        }
        for (int k = 1; k <= N; k++)
            sum += k;
        return sum/N;         // What if N is 0?
    } // avgFirstN()

    The revised avgFirstN() method takes the traditional approach to error handling: Error-handling code is built right into the algorithm. If N happens to be 0 when avgFirstN() is called, the following output will be generated:

    ERROR avgFirstN: N <= 0. Program terminating.

    Java’s Default Exception Handling

    To help detect and handle common runtime errors, Java’s creators incorporated an exception-handling model into the language itself. In the case of our divide-by-zero error, the Java Virtual Machine (JVM) would detect the error and abort the program. To see this, consider the program in Figure [fig-calcavg]. Note that the avgFirstN() method is passed an argument of 0 in the CalcAvgTest.main(). When the JVM detects the error, it will abort the program and print the following message:

    Exception in thread "main" 
       java.lang.ArithmeticException:  / by zero
            at CalcAverage.avgFirstN(Compiled Code)
            at CalcAvgTest.main(CalcAvgTest.java:5)

    The error message describes the error and provides a trace of the method calls, from last to first, that led to the error. This trace shows that the error occurred in the CalcAverage.avgFirstN() method, which was called by the CalcAvgTest.main() method.

    public class CalcAverage {
    
        public double avgFirstN(int N) {
            int sum = 0;
            for (int k = 1; k <= N; k++)
                sum += k;
            return sum/N;         // What if N is 0?
        } // avgFirstN()
    }//CalcAverage
    
    public class CalcAvgTest {
        public static void main(String args[]) {
            CalcAverage ca = new CalcAverage();
            System.out.println( "AVG + " + ca.avgFirstN(0) );        
        }//main
    }//CalcAvgTest

    As this example suggests, Java’s default exception handling is able to detect and handle certain kinds of errors and exceptional conditions. In the next section, we will identify what kinds of conditions are handled by the JVM.


    This page titled 10.1: Handling Exceptional Conditions is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.