Title: Chapter 11: Exception Handling
1Chapter 11 Exception Handling
- Exceptions and Exception Types
- Claiming Exceptions
- Throwing Exceptions
- Catching Exceptions
- Rethrowing Exceptions
- The finally Clause
- Cautions When Using Exceptions
- Creating Your Own Exception Classes (Optional)
2Exception
- An exception represents an error condition that
can occur during the normal course of program
execution. - An exception is an object that represents an
error or exceptional event that has occurred - array index out of bounds IndexOutOfBoundsExceptio
n - trying to open a file that does not exist
FileNotFoundException - trying to call a method that does not exist
NoSuchMethodException - When an exception occurs, the normal sequence of
flow is terminated and the exception handling
routine is executed. - When an exception occurs, an exception is thrown,
when exception handling occurs, the thrown
exception is caught.
3Types of Exceptions
- Normal Exceptions (checked exceptions)
- These exceptions are the ones that every good
program should watch for (for example
FileNotFoundException) you have to handle these
(either catch them or declare that you method can
throw them). - Runtime Exceptions (unchecked exceptions)
- These exceptions have the potential to be in all
code you write (for example IndexOutOfBoundsExcept
ion) you do not need to handle these. - There is a class of exceptions called errors
these are generally irrecoverable (example
VirtualMachineError) These exceptions do not need
to be handled.
4Exceptions and Exception Types
5Exception Handling
- Try, catch, throw, throws and finally
- Try block contains the program block to monitor
the exception. - If an exception occurs within the try block, it
is thrown - A catch block will catch the exception
- Finally means the code has absolutely must be
executed. ie A finally block is ALWAYS executed
no matter how control leaves a try block. This
means even if a return statement is executed in
the try block, and even if control passes to a
catch block.
6try lots of IO code opening and reading
from/to files catch (FileNotFoundException)
tell the user and probably repeat try block
catch (EOF Exception) hit the End Of File
marker early catch (IOException) blanket
catch for all other IO problems finally make
sure to close any files that might be open
7Throws and throw
- throws exceptions -the compiler and user of the
code are aware that this method can produce these
checked exceptions. - Example
- public String wildFileMethod (String fileName)
throws FileNotFoundException, EOFException - code goes here
8Throw
- throw -to introduce a new exception .
- throw an already existing exception type or
create your own. - if (personOnPhone ! babu) throw new
Exception("Stranger on the phone!!")
9Claiming, Throwing, and Catching Exceptions
10Claiming Exceptions
- public void myMethod()
- throws IOException
- public void myMethod()
- throws IOException, OtherException
11Throwing Exceptions
- throw new TheException()
- TheException e new TheException()throw e
12 Example 1
//demonstrate Exception Example
ArrayIndexOutOfBoundException
Class ExcDemo1 Public static void main(String
args) Int numsnew int4 Try
S.o.p(Before exception is generated.) //gener
ate an index out-of-bounds exception Nums710 s
.o.p(this wont be displayed) Catch(ArrayInde
xOutOfBoundsException e) //catch the
exception s.o.p(Index Out OF Bound error)
Finally System.out.println(After the catch
ststement)
13Throwing Exceptions Example
- public Rational divide(Rational r) throws
Exception -
- if (r.numer 0)
-
- throw new Exception("denominator
- cannot be zero")
-
-
- long n numerr.denom
- long d denomr.numer
- return new Rational(n,d)
14Catching Exceptions
- try
-
- statements
-
- catch (Exception1 e)
- handler for exception1
- catch (Exception2 e)
- handler for exception2
- ...
- catch (ExceptionN e)
- handler for exceptionN
15Catching Exceptions
16Example 11.1 Claiming, Throwing, and Catching
Exceptions
- Objective Write a program to test the new
Rational class.
TestRationalException
Rational
Run
17Catching subclass Exceptions
- Class ExDemo2
- public static void main(String args)
- int num4,8,16,32,64,128,256,512)
- int den2,0,4,4,0,8)
- for (int i0Iltnum.lengthi)
- try
- System.out.println(numi/deniis
numi/deni) -
- Catch(ArrayIndexOutOfBoundsExcpetion e)
- //catch the exception
- s.o.p(No matching element found)
- Catch(Throwable e)
- s.o.p(Some Exception occurred)
18Example 11.2 Exceptions in GUI Applications
- An error message appears on the console, but the
GUI application continues running. - Re-run the MenuDemo applet from Example 9.9 and
divide by 0 to see how a GUI deals with unhandled
exceptions.
MenuDemo
Run
19Rethrowing Exceptions
- try
-
- statements
-
- catch(TheException e)
-
- perform operations before exits
- throw e
20The finally Clause
- try
-
- statements
-
- catch(TheException e)
-
- handling e
-
- finally
-
- finalStatements
21Cautions When Using Exceptions
- Exception handling separates error-handling code
from normal programming tasks, thus making
programs easier to read and to modify. Be aware,
however, that exception handling usually requires
more time and resources because it requires
instantiating a new exception object, rolling
back the call stack, and propagating the errors
to the calling methods.
22Example 11.3 (Optional) Creating Your Own
Exception Classes
- Objective This program creates a Java applet for
handling account transactions. The applet
displays the account id and balance, and lets the
user deposit to or withdraw from the account. For
each transaction, a message is displayed to
indicate the status of the transaction
successful or failed. In case of failure, the
failure reason is reported.
23Example 11.3, cont.
Account
InsufficientFundException
NegativeAmountException
AccountApplet
Run