Handling Exceptions - PowerPoint PPT Presentation

1 / 32
About This Presentation
Title:

Handling Exceptions

Description:

If no exception occurs, control transfers to statement following entire try-catch statement ... If an exception in a try block is caught by the first catch ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 33
Provided by: manasi86
Category:

less

Transcript and Presenter's Notes

Title: Handling Exceptions


1
TOPIC 11
  • Handling Exceptions

2
  • /
  • Demonstrates an uncaught exception.

  • /
  • public class Zero
  • //-----------------------------------------------
    ----
  • // Deliberately divides by zero to produce
  • // an exception.
  • //-----------------------------------------------
    ----
  • public static void main(String args)
  • int numerator 10
  • int denominator 0
  •   System.out.println(numerator / denominator)
  • System.out.println(This text will not be
    printed.0
  •  

3
Exception in thread main java.lang.ArithmeticExc
eption / by zero At Zero.main(Zero.java17)
  • java.lang.ArithmeticException indicates which
    exception was thrown.
  • Info about the nature of the error
  • / by zero
  • Call stack trace ? indicates where the exception
    occurred
  • At Zero.main(Zero.java17)
  • Zero.main ? method that generated the error
  • Zero.java17 ? line no. where exception
    occurred

4
An error-handling solution
  • public class Zero
  • public static void main(String args)
  • int numerator 10
  • int denominator 0
  •  
  • if (denominator 0)
  • System.exit(1)
  •  
  • System.out.println(numerator / denominator)

5
  • System.exit() method
  • Current application ends control returns to the
    operating system.
  • Return 1 if an error is causing program
    termination.
  • Return 0 if the program is ending normally.

6
Exception
  • Definition an occurrence of an undesirable
    situation that can be detected during program
    execution
  • Examples
  • division by zero
  • trying to open an input file that does not exist
  • an array index that goes out of bounds

7
Some Terminology
  • Throwing an exception either Java itself or your
    code signals when something unusual happens
  • Handling an exception responding to an exception
    by executing a part of the program specifically
    written for the exception
  • also called catching an exception
  • The normal case is handled in a try block
  • The exceptional case is handled in a catch block
  • The catch block takes a parameter of type
    Exception
  • it is called the catch-block parameter
  • e is a commonly used name for it
  • If an exception is thrown execution in the try
    block ends and control passes to the catch
    block(s) after the try block

8
Java Exception Hierarchy
9
Constructors and Methods of the class Throwable
10
The class Exception and its Subclasses from
java.lang
11
The class Exception and its Subclasses from
java.util
12
The class Exception and its Subclasses from
java.io
13
Javas Exception Class
  • class Exception
  • Subclass of class Throwable
  • Superclass of classes designed to handle
    exceptions
  • Various types of exceptions
  • I/O exceptions
  • Number format exceptions
  • File not found exceptions
  • Array index out of bounds exceptions
  • Various exceptions categorized into separate
    classes and contained in various packages

14
The class Exception and its Constructors
15
Java Exception Classes
16
Exceptions Thrown by Methods
17
Exceptions Thrown by Methods
18
Handling Exceptions within a Program
  • try
  • //statements
  • catch(ExceptionClassName1 objRef1)
  • //exception handler code
  • catch(ExceptionClassName2 objRef2)
  • //exception handler code
  • ...
  • catch(ExceptionClassNameN objRefN)
  • //exception handler code
  • finally

19
Handling Exceptions within a Program
  • try/catch/finally block used to handle exceptions
    within a program
  • try block
  • Includes statements that may generate an
    exception
  • Includes statements that should not be executed
    if an exception occurs
  • If error occurs, execution transfers to
    statements in the catch block
  • If no exception occurs, control transfers to
    statement following entire try-catch statement
  • Followed by zero or more catch blocks
  • May or may not be followed by finally block

20
Handling Exceptions within a Program
  • catch block
  • Heading specifies type of exception it can catch
  • Contains exception handler completely handles
    exception
  • Can catch all exceptions of a specific type or
    all types of exceptions
  • Completes without causing any new exceptions,
    then control transfers to next statement outside
    of try-catch statement
  • If several catch blocks, which one is
    appropriate?
  • Selects the first one with a class (ExceptionType
    ) that matches the thrown exception
  • May or may not be followed by a finally block

21
Handling Exceptions within a Program
  • finally block
  • Code contained in this block always executes
  • try block with no catch block has finally block

22
An Example of Exception Handling
ExceptionDemo try and catch blocks
try block
throw statement
catch block
22
Chapter 8
Java an Introduction to Computer Science
Programming - Walter Savitch
23
Flow of Control with Exception Handling
try System.out.println("Enter number of
donuts") donutCount SavitchIn.readLineInt()
System.out.println("Enter number of
glasses") milkCount SavitchIn.readLineInt()
if (milkCount lt 1)
throw new Exception("Exception No Milk!")
donutsPerGlass donutCount/(double)milkCount
System.out.println(donutCount " donuts.")
System.out.println(milkCount " glasses of
milk.") System.out.println("You have "
donutsPerGlass) catch(Exception e)
System.out.println(e.getMessage())
System.out.println("Go buy some
milk.") System.out.println("End of program.")
Assume user enters a positive number for number
of glasses, so no exception is thrown.
Not executed when there's no exception thrown.
Main method from Exception-Demo program
24
Flow of Control with Exception Handling
try System.out.println("Enter number of
donuts") donutCount SavitchIn.readLineInt()
System.out.println("Enter number of
glasses") milkCount SavitchIn.readLineInt()
if (milkCount lt 1)
throw new Exception("Exception No Milk!")
donutsPerGlass donutCount/(double)milkCount
System.out.println(donutCount " donuts.")
System.out.println(milkCount " glasses of
milk.") System.out.println("You have "
donutsPerGlass) catch(Exception e)
System.out.println(e.getMessage())
System.out.println("Go buy some
milk.") System.out.println("End of program.")
Assume user enters zero or a negative number for
number of glasses, so an exception is thrown.
Not executed when an exception is thrown
Main method from Exception-Demo program
25
  • public class ErrExample1
  • public static void main (Stringargs)
  • int num 13, denom 0, result
  • int array 22, 33, 44
  • try
  • result num / denom
  • result arraynum
  • catch (ArithmeticException error)
  • System.out.println("Arithmetic error")
  • catch (IndexOutOfBoundsException error)
  • System.out.println("Index error")
  • // end main // end class

26
  • int num 13, denom 2, result
  • int array 22, 33, 44
  • try
  • result num / denom
  • result arraynum
  • catch (ArithmeticException error)
  • System.out.println("Arithmetic error")
  • catch (IndexOutOfBoundsException error)
  • System.out.println("Index error")

27
Order of catch Blocks
  • If an exception in a try block is caught by the
    first catch block, the remaining catch blocks are
    ignored
  • Must be careful about order catch blocks are
    listed

28
General error handler
  • try
  • catch (ArithmeticException error) //define
    specific exceptions first
  • System.out.println("Arithmetic error")
  • catch (.. error)
  • System.out.println(. )
  • catch (Exception error) //define general
    exception last
  • System.out.println("ERROR Notify
    Administrator")
  • error.printStackTrace()
  • System.exit(0)

29
Generating an Exception with throw
  • throw new ExceptionType(possibly_some_parameters)
  • ObjectExpression
  • Variable or value of a class that implements the
    Throwable interface
  • i.e. must be an object of class Throwable or a
    subclass of Throwable such as Exception
  • When exception is thrown, JVM looks for a catch
    statement that can handle that specific type of
    exception
  • May be written within a try statement that is
    intended to catch it

30
To catch an ArithmeticException (1)
  • public class Zero
  • public static void main(String args)
  • int numerator 10, denominator 0
  •   try
  • if (denominator 0)
  • throw new ArithmeticException()
  • System.out.println(numerator / denominator)
  • catch (ArithmeticException error)
  • System.out.println(Attempt to divide by
    zero!)

31
Using the Exception getMessage() method
  • public class Zero
  • public static void main(String args)
  • int numerator 10, denominator 0
  •   try
  • System.out.println(numerator / denominator)
  • catch (ArithmeticException error)
  • System.out.println(The official message is
  • error.getMessage())

32
Do more than print error message
  • public class Zero
  • public static void main(String args)
  • int numerator 10 denominator 0
  •   try
  • System.out.println(numerator / denominator)
  • catch (ArithmeticException error)
  • System.out.println(The official message is
  • error.getMessage())
  • System.out.println(Denominator corrected
    to 1)
  • finally
  • System.out.println(numerator / 1)
Write a Comment
User Comments (0)
About PowerShow.com