Title: Handling Exceptions
1TOPIC 11
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 -
-
- Â
3Exception 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
4An 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.
6Exception
- 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
7Some 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
8Java Exception Hierarchy
9Constructors and Methods of the class Throwable
10The class Exception and its Subclasses from
java.lang
11The class Exception and its Subclasses from
java.util
12The class Exception and its Subclasses from
java.io
13Javas 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
14The class Exception and its Constructors
15Java Exception Classes
16Exceptions Thrown by Methods
17Exceptions Thrown by Methods
18Handling 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
-
19Handling 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
20Handling 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
21Handling Exceptions within a Program
- finally block
- Code contained in this block always executes
- try block with no catch block has finally block
22An 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
23Flow 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
24Flow 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")
-
27Order 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
28General 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)
29Generating 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
30To 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!) -
-
31Using 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())
-
-
32Do 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)
-