Exception Handling - PowerPoint PPT Presentation

1 / 46
About This Presentation
Title:

Exception Handling

Description:

try // read two numbers and calculate quotient ... scanner.nextLine(); // discard input so user can try again ... end try. catch ( Exception exception ) ... – PowerPoint PPT presentation

Number of Views:55
Avg rating:3.0/5.0
Slides: 47
Provided by: grego1
Category:

less

Transcript and Presenter's Notes

Title: Exception Handling


1
Exception Handling
  • Chapter 13

2
Exceptions
  • We have already been using exception handling in
    the preceding chapters.
  • Exception handling allows the program to detect
    and error and handle it as it chooses.
  • This might mean some kind of recovery followed by
    continued execution, or some kind of error
    message and termination of the program.

3
Error Handling
  • Before exception handling features were present
    in languages, a program would have to explicitly
    check for errors as it executes.
  • This continual mixing of statements with
    error-checking code can make the code difficult
    to read, modify, maintain, and debug.

4
Exception Handling
  • Exception handling features in modern languages
    like Java allow much of the explicit error
    checking to be avoided.
  • An exception among the statements inside a try
    block will automatically be caught and processed
    by the corresponding catch block.
  • This improves program clarity and makes the
    program easier to maintain.

5
Example
  • The following example asks the user to input two
    integers and divides them.
  • If the user enters 0 for the denominator, an
    exception, ArithmeticException, occurs.
  • If the user enters a string instead of an
    integer, an exception, InputMismatchException,
    occurs.

6
  • // Fig. 13.1 DivideByZeroNoExceptionHandling.java
  • // An application that attempts to divide by
    zero.
  • 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 " )

7
Output
  • Please enter an integer numerator 100
  • Please enter an integer denominator 0
  • Exception in thread "main" java.lang.ArithmeticExc
    eption / by zero
  • at DivideByZeroNoExceptionHandling.quotien
    t(DivideByZeroNoExceptionHandl
  • ing.java10)
  • at DivideByZeroNoExceptionHandling.main(Di
    videByZeroNoExceptionHandling.
  • java22)
  • Press any key to continue...

exception
stack trace
8
Output
  • Please enter an integer numerator 100
  • Please enter an integer denominator hello
  • Exception in thread "main" java.util.InputMismatch
    Exception
  • at java.util.Scanner.throwFor(Scanner.java
    819)
  • at java.util.Scanner.next(Scanner.java143
    1)
  • at java.util.Scanner.nextInt(Scanner.java
    2040)
  • at java.util.Scanner.nextInt(Scanner.java
    2000)
  • at DivideByZeroNoExceptionHandling.main(Di
    videByZeroNoExceptionHandling.
  • java20)
  • Press any key to continue...

9
Example
  • The next example fixes these two problems with
    exception handling.
  • Now, if the user enters a 0 or a string, the user
    is asked to re-enter the value.
  • When a valid value is entered, the program
    proceeds normally.

10
  • // Fig. 13.2 DivideByZeroWithExceptionHandling.ja
    va
  • // An exception-handling example that checks for
    divide-by-zero.
  • 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

11
  • 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

12
Output
  • Please enter an integer numerator 100
  • Please enter an integer denominator 0
  • Exception java.lang.ArithmeticException / by
    zero
  • Zero is an invalid denominator. Please try again.
  • Please enter an integer numerator

13
Output
  • Please enter an integer numerator 100
  • Please enter an integer denominator hello
  • Exception java.util.InputMismatchException
  • You must enter integers. Please try again.
  • Please enter an integer numerator

14
Try-Catch
  • The try block includes statements that may cause
    an exception.
  • Each catch block specifies the type of exception
    it handles.
  • When an exception occurs, control immediately
    goes to the matching catch block.
  • After the catch block, execution resumes
    immediately following the last catch block.

15
The Throws Clause
  • A method should specify the exceptions it throws
    by placing a throws clause after the parameter
    list.
  • The caller should handle this exception or throw
    the exception itself.

16
Java Exception Hierarchy
  • Class Throwable has two subclasses, Exception and
    Error.
  • Errors are rare and should not be caught.
  • Only Throwable objects can be used in exception
    handling.
  • All exceptions inherit from class Exception.
  • The hierarchy is shown on the next slide

17
Portion of Throwable hierarchy
Throwable
Exception
Error
IOException
Runtime Exception
AWTError
ThreadDeath
OutOf MemoryError
ArrayIndexOutOfBoundsException
InputMismatchException
NullPointerException
ClassCastException
ArithmeticException
18
Exceptions
  • There are two kinds of exceptions
  • Unchecked subclasses of RuntimeException and
    Error.
  • Checked subclasses of Exception other than
    subclasses of RuntimeException.
  • Checked exceptions must be caught or declared in
    a throws clause.

19
Exceptions
  • If multiple catch blocks match an exception, only
    the first matching catch block executes.
  • If a catch block for a superclass of an exception
    occurs before the catch block of a subclass of an
    exception causes a compile error.

20
Finally Block
  • Resources that are opened may need to be closed
    during exception handling.
  • The finally block can be used for this.
  • The finally block appears after the last catch
    block.
  • It executes regardless of whether an exception
    occurs if the try block ended with a return,
    break, or continue statement.
  • It will not execute if a System.exit occurs first.

21
Nested Exceptions
  • If an exception is not caught, any finally block
    runs, then control passes to the next outer try
    block.
  • This can occur through many levels of nesting
    until an appropriate catch block is found.
  • The finally block runs even if a catch block
    throws an exception.

22
  • // Fig. 13.7 UsingExceptions.java
  • // Demonstrating getMessage and printStackTrace
    from class Exception.
  • public class UsingExceptions
  • public static void main( String args )
  • try
  • method1() // call method1
  • // end try
  • catch ( Exception exception ) // catch
    exception thrown in method1
  • System.err.printf( "s\n\n",
    exception.getMessage() )
  • exception.printStackTrace() // print
    exception stack trace
  • // obtain the stack-trace information
  • StackTraceElement traceElements
    exception.getStackTrace()

23
  • // loop through traceElements to get
    exception description
  • for ( StackTraceElement element
    traceElements )
  • System.out.printf( "s\t",
    element.getClassName() )
  • System.out.printf( "s\t",
    element.getFileName() )
  • System.out.printf( "s\t",
    element.getLineNumber() )
  • System.out.printf( "s\n",
    element.getMethodName() )
  • // end for
  • // end catch
  • // end main
  • // call method2 throw exceptions back to main
  • public static void method1() throws Exception
  • method2()
  • // end method method1
  • // call method3 throw exceptions back to
    method1
  • public static void method2() throws Exception

24
  • // throw Exception back to method2
  • public static void method3() throws Exception
  • throw new Exception( "Exception thrown in
    method3" )
  • // end method method3
  • // end class UsingExceptions

25
Output
  • Exception thrown in method3
  • java.lang.Exception Exception thrown in method3
  • at UsingExceptions.method3(UsingExceptions
    .java49)
  • at UsingExceptions.method2(UsingExceptions
    .java43)
  • at UsingExceptions.method1(UsingExceptions
    .java37)
  • at UsingExceptions.main(UsingExceptions.ja
    va10)
  • Stack trace from getStackTrace
  • Class File Line
    Method
  • UsingExceptions UsingExceptions.java 49
    method3
  • UsingExceptions UsingExceptions.java 43
    method2
  • UsingExceptions UsingExceptions.java 37
    method1
  • UsingExceptions UsingExceptions.java 10
    main
  • Press any key to continue...

26
Throwing Exceptions
  • A program can rethrow an exception by catching it
    and throwing it again.
  • A program can also create and throw a new
    exception using the throw statement.

27
Stack Unwinding
  • When an exception is thrown in a method but not
    caught, that method terminates and an attempt is
    made to catch the exception in the calling
    method.
  • This is called stack unwinding.
  • Each method call is placed on the stack, so as
    these calls terminate, the stack is unwound.
  • If no catch block ever catches it, a compile
    error occurs.

28
  • // Fig. 13.6 UsingExceptions.java
  • // Demonstration of stack unwinding.
  • public class UsingExceptions
  • public static void main( String args )
  • try // call throwException to demonstrate
    stack unwinding
  • throwException()
  • // end try
  • catch ( Exception exception ) // exception
    thrown in throwException
  • System.err.println( "Exception handled
    in main" )
  • // end catch
  • // end main

29
  • // throwException throws exception that is not
    caught in this method
  • public static void throwException() throws
    Exception
  • try // throw an exception and catch it in
    main
  • System.out.println( "Method
    throwException" )
  • throw new Exception() // generate
    exception
  • // end try
  • catch ( RuntimeException runtimeException )
    // catch incorrect type
  • System.err.println( "Exception handled
    in method throwException" )
  • // end catch
  • finally // finally block always executes
  • System.err.println( "Finally is always
    executed" )
  • // end finally
  • // end method throwException
  • // end class UsingExceptions

30
Output
  • Method throwException
  • Finally is always executed
  • Exception handled in main
  • Press any key to continue...

31
printStackTrace
  • Class Throwable has a printStackTrace method.
  • This prints information from the call stack.
  • There is also a getStackTrace method that gets
    the information from the call stack.
  • This lets the program format it itself.
  • getMethod gets the message string in the
    exception.

32
  • // Fig. 13.7 UsingExceptions.java
  • // Demonstrating getMessage and printStackTrace
    from class Exception.
  • public class UsingExceptions
  • public static void main( String args )
  • try
  • method1() // call method1
  • // end try
  • catch ( Exception exception ) // catch
    exception thrown in method1
  • System.err.printf( "s\n\n",
    exception.getMessage() )
  • exception.printStackTrace() // print
    exception stack trace
  • // obtain the stack-trace information
  • StackTraceElement traceElements
    exception.getStackTrace()

33
  • // loop through traceElements to get
    exception description
  • for ( StackTraceElement element
    traceElements )
  • System.out.printf( "s\t",
    element.getClassName() )
  • System.out.printf( "s\t",
    element.getFileName() )
  • System.out.printf( "s\t",
    element.getLineNumber() )
  • System.out.printf( "s\n",
    element.getMethodName() )
  • // end for
  • // end catch
  • // end main

34
  • // call method2 throw exceptions back to main
  • public static void method1() throws Exception
  • method2()
  • // end method method1
  • // call method3 throw exceptions back to
    method1
  • public static void method2() throws Exception
  • method3()
  • // end method method2
  • // throw Exception back to method2
  • public static void method3() throws Exception
  • throw new Exception( "Exception thrown in
    method3" )
  • // end method method3
  • // end class UsingExceptions

35
  • Exception thrown in method3
  • java.lang.Exception Exception thrown in method3
  • at UsingExceptions.method3(UsingExceptions
    .java49)
  • at UsingExceptions.method2(UsingExceptions
    .java43)
  • at UsingExceptions.method1(UsingExceptions
    .java37)
  • at UsingExceptions.main(UsingExceptions.ja
    va10)
  • Stack trace from getStackTrace
  • Class File Line
    Method
  • UsingExceptions UsingExceptions.java 49
    method3
  • UsingExceptions UsingExceptions.java 43
    method2
  • UsingExceptions UsingExceptions.java 37
    method1
  • UsingExceptions UsingExceptions.java 10
    main
  • Press any key to continue...

36
Chained Exceptions
  • In a catch block, a program can catch an
    exception of one type, but then throw an
    exception of a different type.
  • The new exception can wrap the first exception so
    that its information is not lost.
  • This is called a chained exception.

37
  • // Fig. 13.8 UsingChainedExceptions.java
  • // Demonstrating chained exceptions.
  • public class UsingChainedExceptions
  • public static void main( String args )
  • try
  • method1() // call method1
  • // end try
  • catch ( Exception exception ) // exceptions
    thrown from method1
  • exception.printStackTrace()
  • // end catch
  • // end main

38
  • // call method2 throw exceptions back to main
  • public static void method1() throws Exception
  • try
  • method2() // call method2
  • // end try
  • catch ( Exception exception ) // exception
    thrown from method2
  • throw new Exception( "Exception thrown
    in method1", exception )
  • // end try
  • // end method method1

39
  • // call method3 throw exceptions back to
    method1
  • public static void method2() throws Exception
  • try
  • method3() // call method3
  • // end try
  • catch ( Exception exception ) // exception
    thrown from method3
  • throw new Exception( "Exception thrown
    in method2", exception )
  • // end catch
  • // end method method2
  • // throw Exception back to method2
  • public static void method3() throws Exception
  • throw new Exception( "Exception thrown in
    method3" )
  • // end method method3
  • // end class UsingChainedExceptions

40
Output
  • java.lang.Exception Exception thrown in method1
  • at UsingChainedExceptions.method1(UsingCha
    inedExceptions.java27)
  • at UsingChainedExceptions.main(UsingChaine
    dExceptions.java10)
  • Caused by java.lang.Exception Exception thrown
    in method2
  • at UsingChainedExceptions.method2(UsingCha
    inedExceptions.java40)
  • at UsingChainedExceptions.method1(UsingCha
    inedExceptions.java23)
  • ... 1 more
  • Caused by java.lang.Exception Exception thrown
    in method3
  • at UsingChainedExceptions.method3(UsingCha
    inedExceptions.java47)
  • at UsingChainedExceptions.method2(UsingCha
    inedExceptions.java36)
  • ... 2 more
  • Press any key to continue...

41
New Exception Types
  • Most of the time programmers make use of existing
    exception types.
  • This is preferred to since others will be
    familiar with standard exception types.
  • Sometimes you may find it useful to create new
    exception types, such as in the case where you
    are developing a library for others to use.

42
Preconditions and Postconditions
  • Precondition a condition that must be true when
    a method is called.
  • Postcondition a condition that is true after a
    method executes.
  • Providing these in your documentation will help
    programmers use your methods.
  • It can also help to guide you in writing the
    method.

43
Assertions
  • When developing and debugging code, it is useful
    to check that certain conditions are true as the
    code executes.
  • This is the purpose of assertions.

44
Creating Assertions
  • Two forms of creating assertions
  • assert expression
  • assert expression1 expression2
  • The first form throws an AssertionError if the
    expression is false.
  • The second form throws an AssertionError with
    expression2 as the error message if expression1
    is false.

45
Enabling Assertions
  • Assertions are disabled by default.
  • To enable assertions, when executing, use the ea
    option
  • java ea AssertTest

46
End of Slides
Write a Comment
User Comments (0)
About PowerShow.com