Exception Handling - PowerPoint PPT Presentation

1 / 32
About This Presentation
Title:

Exception Handling

Description:

try blocks. Throwing and catching exceptions. Constructors, finalizers and ... if no exception is generated, the finally block is done after the try block ... – PowerPoint PPT presentation

Number of Views:85
Avg rating:3.0/5.0
Slides: 33
Provided by: joek8
Category:

less

Transcript and Presenter's Notes

Title: Exception Handling


1
Exception Handling
  • Joe Komar

2
Overview
  • When to use exception handling
  • Java Exception Handling
  • try blocks
  • Throwing and catching exceptions
  • Constructors, finalizers and exception handling
  • finally block
  • printStackTrace and getMessage

3
Exception Handling
  • Similar to the established C methodology
  • Synchronous exceptions (divide by zero) versus
    asynchronous exceptions (interrupts)
  • Improves a programs fault tolerance
  • Build in from the beginning

4
Exceptions
  • Exception -- thrown by program or runtime
    environment and can be caught and handled
  • Error -- similar to an exception but represents
    an unrecoverable situation and should not be
    handled
  • Java
  • Exception and Error classes derived from the
    Throwable class
  • Specific exceptions and errors derived from their
    classes

5
Exception Execution Flow
  • Distinguish Exception flow from Normal flow
  • Debugging is made easier (pinpoint errors)
  • Java API classes often throw exceptions, letting
    the programmer decide what to do with them
  • Normal flow is typically 20 of the total code
  • Some programs should never abnormally abort
  • Deal with exceptions by
  • choosing not to handle them (abnormal abort)
  • handle the exception where it occurs
  • handle the exception at another point (throws)

6
Use Exception Handling To..
  • process where method is unable to complete its
    task
  • process where components arent geared to handle
    them
  • process where components are widely used and
    cannot handle themselves
  • on large projects to handle exceptions in a
    uniform way

7
The try Statement
  • The try statement identifies a block of
    statements that may throw an exception
  • There can be a number of catch blocks following
    the try block that can process different types of
    errors

try statement-list catch (exception-class1
variable) statement-list catch
(exception-class2 variable) statement-list
catch .
8
The finally Clause
  • Executed no matter how the try block is exited
  • if no exception is generated, the finally block
    is done after the try block
  • if an exception occurs, the appropriate catch
    block is executed and then the finally block
  • A finally block should be listed after all catch
    blocks
  • Typically used to make sure that some section of
    code is always executed no matter what exceptions
    might occur

9
Unhandled Exception
// Throws an Exception public class Zero
public static void main (String args) int
numerator 10 int denominator
0 System.out.println (numerator /
denominator) //method main // class Zero
Java.lang.ArithmeticException / by zero
at Zero.main(Zero.java7)
10
Adding Example
import java.io. public class Adding
public static void main (String args)
int num1 User_Reader.get_integer ("Enter a
number ") int num2 User_Reader.get_int
eger ("Enter another number ")
System.out.println ("The Sum is " (num1
num2)) // method main // class Adding
11
Adding (contd)
class User_Reader public static int
get_integer (String prompt)
BufferedReader stdin new BufferedReader
(new InputStreamReader (System.in),1)
int number 0 boolean valid false
12
Adding (contd)
while (! valid) System.out.print
(prompt) System.out.flush ()
try number
Integer.parseInt (stdin.readLine())
valid true catch
(NumberFormatException exception)
System.out.println ("Invalid input. Try
again.") catch (IOException
exception) System.out.println
("Input problem. Terminating.")
System.exit(0) // while
loop return number // method
get_integer // class User_Reader
13
Adding Output
Normal Execution
Exception handling
Enter a number 8 Enter another number
joe Invalid input. Try again. Enter another
number 34 The Sum is 42
Enter a number 6 Enter another number 56 The
Sum is 62
14
throw Example
// Definition of class DivideByZeroException. //
Used to throw an exception when a //
divide-by-zero is attempted. public class
DivideByZeroException extends
ArithmeticException public
DivideByZeroException() super(
"Attempted to divide by zero" ) public
DivideByZeroException( String message )
super( message )
15
throw Example
import java.io. public class DivideByZeroTest
public static void main (String args)
throws IOException BufferedReader keyIn
new BufferedReader( new InputStreamReader(Sys
tem.in),1) String answer "Y"
16
throw Example
do System.out.print("Enter numerator
") String numerator keyIn.readLine() System.
out.print("Enter denominator ") String
denominator keyIn.readLine() try
int number1 Integer.parseInt(numerator) i
nt number2 Integer.parseInt(denominator) doub
le result quotient(number1, number2) System.o
ut.println("Result is " result)
17
throw Example
catch ( NumberFormatException nfe )
System.out.println( "You
must enter two integers " "Invalid
Number Format") catch (
DivideByZeroException dbze )
System.out.println( "Attempted to
Divide by Zero") finally
System.out.println( "Do
you want to go again (Y or N) ") answer
(keyIn.readLine()).toUpperCase()
while(!answer.equals("N")) //main
18
throw Example
// Definition of method quotient. Used to
demonstrate // throwing an exception when a
divide-by-zero error // is encountered.
public static double quotient( int numerator, int
denominator ) throws DivideByZeroException
if ( denominator 0 ) throw
new DivideByZeroException() return (
double ) numerator / denominator //class
19
throw Example
20
Catching Exceptions
  • Each catch block names the type of exception
    caught
  • catch (Exception e) catches all errors
  • If no catch block in local code, then proceeds to
    search in calling code, etc.
  • If never caught, applications abort, GUI based
    (applications and applets) return to regular
    event handling
  • A catch block can rethrow an exception
  • throw e

21
throws Clause
  • Lists exceptions that can be thrown by a method
  • Dont need to list errors or runtime exceptions
    (e.g. NullPointerException)
  • Checked exceptions the method could throw must
    be listed
  • catch-or-declare requirement -- either deal
    with it or include it in a throws clause

22
Constructors, finalizers, etc.
  • Constructors should throw an exception if the
    object is not created properly
  • Objects not created properly are marked for
    garbage collection
  • Before garbage collection, the finalize method is
    called
  • A catch block can catch a superclass, therefore
    catching all subclasses

23
The finally block
  • Executed no matter how the try block is exited
  • if no exception is generated, the finally block
    is done after the try block
  • if an exception occurs, the appropriate catch
    block is executed and then the finally block
  • A finally block should be listed after all catch
    blocks
  • Typically used to make sure that some section of
    code is always executed no matter what exceptions
    might occur

24
Integrated example
// Demonstration of the try-catch-finally //
exception handling mechanism. public class
UsingExceptions public static void main(
String args ) try
throwException() catch ( Exception
e ) System.err.println(
"Exception handled in main" )
doesNotThrowException()
25
Integrated example
public static void throwException() throws
Exception // Throw an exception and
immediately catch it. try
System.out.println( "Method throwException" )
throw new Exception() // generate
exception catch( Exception e )
System.err.println(
"Exception handled in method throwException" )
throw e // rethrow e for further
processing // any code here would not
be reached
26
Integrated example
finally System.err.println(
"Finally executed in throwException" )
// any code here would not be reached

27
Integrated example
public static void doesNotThrowException()
try System.out.println( "Method
doesNotThrowException" ) catch(
Exception e ) System.err.println(
e.toString() ) finally
System.err.println( "Finally executed
in doesNotThrowException" )
System.out.println( "End of method
doesNotThrowException" )
28
Integrated example
Method throwException Exception handled in method
throwException Finally executed in
throwException Exception handled in main Method
doesNotThrowException Finally executed in
doesNotThrowException End of method
doesNotThrowException
29
printStackTrace and getMessage
// Demonstrating the getMessage and
printStackTrace // methods inherited into all
exception classes. public class UsingExceptions2
public static void main( String args )
try method1()
catch ( Exception e )
System.err.println( e.getMessage() "\n" )
e.printStackTrace()
30
printStackTrace and getMessage
public static void method1() throws Exception
method2() public static void
method2() throws Exception method3()
public static void method3() throws
Exception throw new Exception(
"Exception thrown in method3" )
31
printStackTrace and getMessage
Exception thrown in method3 java.lang.Exception
Exception thrown in method3 at
UsingExceptions.method3(UsingExceptions.java28)
at UsingExceptions.method2(UsingExceptions.
java23) at UsingExceptions.method1(UsingE
xceptions.java18) at UsingExceptions.main
(UsingExceptions.java8)
32
Summary
  • When to use exception handling
  • Java Exception Handling
  • try blocks
  • Throwing and catching exceptions
  • Constructors, finalizers and exception handling
  • finally block
  • printStackTrace and getMessage
Write a Comment
User Comments (0)
About PowerShow.com