Title: Chapter 8-Exception Handling/ Robust Programming
1Chapter 8-Exception Handling/ Robust Programming
2Overview
- What is Exception Handling/Robust Programming.
- Exception Handling in Java.
- Trying/catching exceptions.
- Creating/throwing exceptions.
- Guiding principles of exception handling.
- Review.
3Exception Handling/Robust Programming
If houses were built like programs, the first
woodpecker to come along would destroy all of
civilization as we know it. -Lame CS Joke
4Why robust programming?
- Imagine you are typing your final the night
before it is due. You have just finished your
paper and want to print it out to go over it.
Unfortunately, your printer cable wasnt plugged
in all the way, giving a fatal error and locking
up all of your computer, causing you to lose all
of your 15 page paper (Save often!). This is why
you want robust programming.
5Robust programming
- So far we have been concentrating on learning the
basics of programming and Java. Little attention
has been paid to how fragile our programs are,
what happens when the user enters something
wrong, etc. These are things that MUST be
considered when you get to more advanced levels
of programming. - We have been programming for the general case.
Once that works, program for the exceptional
case.
6Robust Programming Principles
- When an error occurs
- Try to return to a safe state and let the user
continue processing. - If nothing else, at least allow the user to save
their work and end the program gracefully. - You should always at least allow the user to save
their work before crashing!
7Detecting Errors
- The detection of errors may not always occur near
where the error occurs. You may have called 5
different methods before you find an error in the
original user input. Thus error detection is
often done out of context from where the error
occurs. Some system must exist for putting errors
into some context before they can be dealt with.
Java has a nice system of exception handling for
this.
8Exception Handling in Java
9Java exception handling
- When a method detects an error, an error message
called an exception is created and thrown to the
methods that called the current method. - If one of these other methods thinks they can
deal with the error, they will catch the method.
If it turns out that they cant deal with the
whole error, they will re-throw the exception so
the next method can take a stab at it. - Only one method at a time can catch an exception.
They receive the exceptions in reverse order of
how the methods were called.
10Exception handling example
11Trying and catching exceptions
12How to catch an exception
- When we are running code that may produce an
exception, we need to be able to catch that
exception.This is done with try and catch blocks.
- We put the code that may produce an exception in
a try block. - We put the code on how to deal with an exception
in a catch block.
13Try/catch
try //code you want to try //may produce an
exception catch(Exception e) //deal with the
exception.
14Try details
- When an exception is thrown inside of a try
block, execution stops inside of the try block
and it will start up in the corresponding catch
block. Wont return to that point in the try
block after the catch clause, either. It will
continue on after the try/catch blocks.
15Catch details
- You specify what kind of exception you are
catching. - IOException
- NumberFormatException
- etc.
- If you are not able to completely deal with the
exception, do what you can and then re-throw it. - Can have more than one catch block for a single
try block.
16Multiple catches.
try //code to try catch(NumberFormatException
e) //deal with number format
error catch(IOException e) //deal with IO
error catch(Exception e) //deal with general
Error.
17Multiple catches.
- Put them in order from the most specific to the
least specific. - First one that matches will be executed.
- Remember about inheritance. Every exception class
tends to inherit from Exception. So every
exception will be of type Exception.
18Finally
- There is an extra block that we can have that
will be performed whether an exception happens or
not. It is called finally. - Will even be executed if an exception is thrown
that is not caught by your catch statements.
19finally
try //code to try catch(Exception
e) //deal with exception finally //code
you always want to run.
20Try/Catch examples
- See SavitchIn for numerous Try/Catch examples.
Since SavitchIn is catching all of these
exceptions and dealing with them, you have not
had to deal with this at all up till now(I/O
tends to cause a lot of exceptions. Without
SavitchIn, we would have had to deal with
exception handling back in chapter 1).
21Useful exception methods
- getMessage()Returns as a string any message that
someone gave the exception when they created it. - printStackTrace() Prints out to the screen the
stack of methods that are currently being run.
The top method is the one that the error
originally occurred in. Automatically run if the
exception is not caught.
22Throwing/creating exceptions
23Creating exception classes
- Quite often it is easier to create a new
exception class for the new kinds of errors that
you want to throw(that way you dont get them
confused with pre-defined ones). - Inherit from the Exception or Throwable class.
- Quite often the exception classes are pretty
empty.
24Exception class creation
public class DivideByZeroException extends
Exception public DivideByZeroException() s
uper(Division by zero.) public
DivideByZeroException( String
message) super(message)
25Detecting and throwing exceptions
- If we detect a problem in the code that we are
unable to deal with, we can create an exception
and throw it out to the methods that called us to
see if they know what to do with it. - We use the throw command, and we throw some sort
of exception object.
26throwing
if(lterror conditiongt) throw new
ltAppropriateExceptiongt() or throw new
ltAppropriateExceptiongt(String) if(denominator
0) throw new DivideByZeroException() or thro
w new DivideByZeroException( Division by
zero!)
27Alternate way of creating exceptions and throwing.
if(denominator 0) DivideByZeroException e
new DivideByZeroException() throw e
28Re-throwing exceptions
- If we catch an exception and cant completely
deal with it, we want to re-throw the exception.
29Re-throwing example
try //some code that might produce //a
DivideByZeroException catch(DivideByZeroExceptio
n ex) //do some processing. //cant
completely deal with it though. throw ex
30Throwing in public
- Whenever a method may throw an exception, we want
to advertise this so that anyone using that
method can prepare for the exception if need be. - We must include a throws clause in our method
declaration.
31Advertising exceptions
public void method1() throws SomeException
public double division(double num, double
den) throws DivideByZeroException
32Guiding principles on exception handling
33Never squelch an exception
try //some code that might produce an //
Exception catch(Exception e) //catch all
exceptions
34Handling in moderation.
- Exception handling is a bit of a balancing act.
- You dont want to handle all exceptions yourself,
as sometimes you dont know how to handle the
problem, so it is good to pass on exceptions or
throw them. - You want to handle the exceptions you do know
what to do with, else your fellow programmers
will get angry at you for never dealing with any
of your problems and just passing them on.
35Exceptions you dont usually worry about
- Errors (NoSuchMethod, OutOfMemory)
- Dont usually need to catch ArrayIndexOutOfBounds
exceptions, except in this next homework.
36When not to use exception handling.
- If you can detect an error before it is going to
occur, do it. It will save your program time. - For example, if I was reading in numbers to
divide and the denominator was given to be zero,
I could deal with the error right there instead
of calling the division function and creating an
exception.
37Exception Handling Review
38Robust Programming Review
- When you first encounter an error, what is the
first thing that you should try to do? - What is the least that you should do when you
encounter an unrecoverable error?
39Exception Handling review.
- What word do we use if we think some code might
not execute correctly or might result in an
exception? - How do we receive an exception that might be
produced in some code?
40Exception Handling review
- Put code around the following snippet to properly
receive the WeirdException exception
System.out.println(Enter name ) String name
SavitchIn.readLine() String starWarsName
weirdMethod(name) System.out.println(Your star
wars name starWarsName)
41Exception Handling Review
- Put the proper code in the following snippet to
be prepared to receive the NumberFormatException
and the IOException exceptions(IOException is the
more general)
System.out.println(Enter an integer ) int
someNum SavitchIn.readLineInt() double
otherNum weirdMethod(someNum) System.out.printl
n(The answerotherNum)
42Exception Handling Review
- Create a new exception class called
HalloweenException. - Write some code to create and throw a
HalloweenException. - Give the method declaration for a public method
called Scary that has no parameters, returns
nothing, but might produce a HalloweenException.
43Exception Handling Review
- Which is faster, detecting an error before
calling a method that will produce an exception,
or just calling the function and later dealing
with the exception?