Java Exception Handling

Java Exception Handling

Moutain State University Java Study Notes
(Week 1 CIS 220 Computer Science II)

Java exception handling is based in part on Andrew Koenig's and Bjarne
Stroustrup's paper, "Exception Handling for C++ (revised).
(Reference: A. Koenig, and B. Stroustrup, "Exception Handling for C++
(revised)." Proceedings of the Usenix C++ Conference, pp. 149-176, San
Francisco, April 1990.)

Only classes that extend THROWABLE (package.java.lang) dirctly or indirectly
can be used with exception handling.

Error Handling Overview Psuedocode

Perform a task

If the preceeding task did not execute correctly
        Perform error processing

Perform next task

If the preceeding task did not execute correctly
        Perform error processing

Public Class without Exception Handling

// Intro to Java page 454 figure 11.1
// Integer division WITHOUT exception handling
import java.util.Scanner;

public class DivideByZeroNoExceptionHandling
{
// demonstrates throwing an exception when a divide-by-zero occurs
    public static int quotient( int numerator, int denominator )
    {
        return numerator / denominator; //
possible division by zero
    } // end method quotient

    public static void main( String[] args )
    {
        Scanner scanner = new Scanner(
System.in ); // scanner for input

        System.out.print( "Please enter an
integer numerator: " );
        int numerator = scanner.nextInt();
        System.out.print( "Please enter an
integer denominator: " );
        int denominator = scanner.nextInt();

        int result = quotient( numerator,
denominator );
        System.out.printf(
            "\nResult: %d
/ %d = %d\n", numerator, denominator, result );
    } // end method main
} // end class DivideByZeroNoExceptionHandling

RETURNS:
Please enter an integer numerator: 100
Please enter an integer denominator: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at
DivideByZeroNoExceptionHandling.quotient(DivideByZeroNoExceptionHandling.java:10)
at DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:22)
OR:
Please enter an integer numerator: 100
Please enter an integer denominator: hello
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:20)

Public Class With Exception Handling

// Java intro to programming page 456 Figure 11.2
// Handling ArithmeticExceptions and InputMismatchExceptions

import java.util.InputMismatchException;
import java.util.Scanner;

public class DivideByZeroWithExceptionHandling
{
    // demonstrates throwing an exception when a divide-by-zero
occurs
    public static int quotient( int numerator, int denominator )
    throws ArithmeticException
    {
        return numerator / denominator; //
possible division by zero
    } // end method quotient

    public static void main( String[] args )
    {
        Scanner scanner = new Scanner(
System.in ); // scanner for input
        boolean continueLoop = true; //
determines if more input is needed

        do
        {
            try // read
two numbers and calculate quotient
            {
               
System.out.print( "Please enter an integer numerator: ");
               
int numerator = scanner.nextInt();
               
System.out.print( "Please enter an integer denominator: " );
               
int denominator = scanner.nextInt();

               
int result = quotient( numerator, denominator );
               
System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result );
               
continueLoop = false; // input successful; end looping
            } // end try
            catch (
InputMismatchException inputMismatchException )
            {
               
System.err.printf( "\nException: %s\n",
               
inputMismatchException );
               
scanner.nextLine(); // discard input so user can try again
               
System.out.println(
               
"You must enter integers. Please try again. \n" );
            } // end
catch
            catch
(ArithmeticException arithmeticException )
            {
               
System.err.printf( "\nException: %s\n", arithmeticException );
               
System.out.println(
               
"Zero is an invalid denominator. Please try again.\n" );
            } // end
catch
        } while ( continueLoop ); // end
do…while
    }  // end method main
} // end class DivideByZeroWithExceptionHandling

Error Prevention Tip:

Read the online API documentation for a method before using that method in a
program. The documentation specifies the exceptions thrown by a method and
indicates reasons why exceptions occur. Next, read the online API documentation
for the specified exception classes. The documentation for an exception class
typically contains potential reasons that such exceptions occur. Finally,
provide for handling those exceptions in your program.
Java Documentation:

http://download.oracle.com/javase/1.4.2/docs/api/overview-summary.html

When to use exception handling?

Exception handling is designed to process synchronous errors, which occur
when a statement executes.

Java Exception Hierarchy

All Java exception classes inherit directly or indirectly from class
Exception, forming an inheritance hierarchy.

The class Throwable is the superclass of class exception. Class Throwable has
two subclasses: Exception and Error.
Class Throwable API documentation:

http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html

printStackTrace, getStackTrace and getMessage

printStackTrace – Outputs to the standard error stream the
stack trace.
getStackTrace – Retrieves the stack-trace information that must
be printed by printStackTrace.
getMessage – Returns the descriptive string stored in an
exception.

Chained Exceptions

Chained exceptions enable a exception object to maintain the complex
stack-trace information from the original exception.

Declaring New Exception Types

A new exception class must extend an existing exception class to ensure that
the class can be used with the exception-handling mechanism. Like any other
class, an exception class can contain fields and methods. However, a typical new
exception class contains only for constructors; one that takes no arguments and
passes a default error message String to the superclass constructor; one that
recieves a customized error message as a String and passes it to the superclass
constructor; one that recieves a customized error message as a String and a
Throwable (for chaning exceptions) and passes both to the superclass
constructor; and one that receives a Throwable (for chaining exceptions) and
passes it to the superclass constructor.

Preconditions and Postconditions

Programmers spend a signifcant amounts of time maintaining and debugging
code. To facilitate these tasks and to improve the overall design, they can
specifiy the expected states before and after a method's execution. A
precondition must be true when a method is invoked. A postcondition is true
after the method is invoked.

Assertions

When implementing and debugging a class, it's sometimes useful to state
conditions that should be true at a paticular point in a method. These
conditions, called assertions, help ensure a program's validity by catching
potential bugs and identifying possible logic errors during development.

Source: P. Deitel, and H. Deitel (2010). Java, Late Objects Version, How To
Program (Eight Edition) pp 452-477, Upper Saddle River, New Jersey: Pearson
Education, Inc


http://www.amazon.com/Java-How-Program-Objects-Version/dp/0136123716

0
  Related Posts