Chapter 8-Exception Handling/ Robust Programming - PowerPoint PPT Presentation

About This Presentation
Title:

Chapter 8-Exception Handling/ Robust Programming

Description:

IOException. NumberFormatException. etc. ... catch(IOException e) //deal with IO error. catch(Exception e) //deal with general Error. ... – PowerPoint PPT presentation

Number of Views:27
Avg rating:3.0/5.0
Slides: 44
Provided by: erics84
Category:

less

Transcript and Presenter's Notes

Title: Chapter 8-Exception Handling/ Robust Programming


1
Chapter 8-Exception Handling/ Robust Programming
2
Overview
  • What is Exception Handling/Robust Programming.
  • Exception Handling in Java.
  • Trying/catching exceptions.
  • Creating/throwing exceptions.
  • Guiding principles of exception handling.
  • Review.

3
Exception 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
4
Why 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.

5
Robust 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.

6
Robust 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!

7
Detecting 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.

8
Exception Handling in Java
9
Java 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.

10
Exception handling example
  • I need a few volunteers.

11
Trying and catching exceptions
12
How 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.

13
Try/catch
try //code you want to try //may produce an
exception catch(Exception e) //deal with the
exception.
14
Try 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.

15
Catch 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.

16
Multiple 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.
17
Multiple 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.

18
Finally
  • 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.

19
finally
try //code to try catch(Exception
e) //deal with exception finally //code
you always want to run.
20
Try/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).

21
Useful 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.

22
Throwing/creating exceptions
23
Creating 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.

24
Exception class creation
public class DivideByZeroException extends
Exception public DivideByZeroException() s
uper(Division by zero.) public
DivideByZeroException( String
message) super(message)
25
Detecting 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.

26
throwing
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!)
27
Alternate way of creating exceptions and throwing.
if(denominator 0) DivideByZeroException e
new DivideByZeroException() throw e
28
Re-throwing exceptions
  • If we catch an exception and cant completely
    deal with it, we want to re-throw the exception.

29
Re-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
30
Throwing 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.

31
Advertising exceptions
public void method1() throws SomeException
public double division(double num, double
den) throws DivideByZeroException
32
Guiding principles on exception handling
33
Never squelch an exception
try //some code that might produce an //
Exception catch(Exception e) //catch all
exceptions
34
Handling 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.

35
Exceptions you dont usually worry about
  • Errors (NoSuchMethod, OutOfMemory)
  • Dont usually need to catch ArrayIndexOutOfBounds
    exceptions, except in this next homework.

36
When 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.

37
Exception Handling Review
38
Robust 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?

39
Exception 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?

40
Exception 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)
41
Exception 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)
42
Exception 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.

43
Exception 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?
Write a Comment
User Comments (0)
About PowerShow.com