chapter 8-exception handling/ robust programming

43
Chapter 8-Exception Handling/ Robust Programming

Upload: peter-young

Post on 18-Jan-2018

237 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Chapter 8-Exception Handling/ Robust Programming

Chapter 8-Exception Handling/ Robust Programming

Page 2: Chapter 8-Exception Handling/ Robust Programming

Overview

What is Exception Handling/Robust Programming.

Exception Handling in Java. Trying/catching exceptions. Creating/throwing exceptions. Guiding principles of exception

handling. Review.

Page 3: Chapter 8-Exception Handling/ Robust Programming

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

Page 4: Chapter 8-Exception Handling/ Robust Programming

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 wasn’t 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.

Page 5: Chapter 8-Exception Handling/ Robust Programming

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.

Page 6: Chapter 8-Exception Handling/ Robust Programming

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!

Page 7: Chapter 8-Exception Handling/ Robust Programming

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.

Page 8: Chapter 8-Exception Handling/ Robust Programming

Exception Handling in Java

Page 9: Chapter 8-Exception Handling/ Robust Programming

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 can’t 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.

Page 10: Chapter 8-Exception Handling/ Robust Programming

Exception handling example

I need a few volunteers.

Page 11: Chapter 8-Exception Handling/ Robust Programming

Trying and catching exceptions

Page 12: Chapter 8-Exception Handling/ Robust Programming

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.

Page 13: Chapter 8-Exception Handling/ Robust Programming

Try/catch

try{

//code you want to try//may produce an exception

}catch(Exception e){

//deal with the exception.}

Page 14: Chapter 8-Exception Handling/ Robust Programming

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. Won’t return to that point in the try block after the catch clause, either. It will continue on after the try/catch blocks.

Page 15: Chapter 8-Exception Handling/ Robust Programming

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.

Page 16: Chapter 8-Exception Handling/ Robust Programming

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

Page 17: Chapter 8-Exception Handling/ Robust Programming

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.

Page 18: Chapter 8-Exception Handling/ Robust Programming

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.

Page 19: Chapter 8-Exception Handling/ Robust Programming

finally

try{

//code to try}catch(Exception e){

//deal with exception}finally{

//code you always want to run.}

Page 20: Chapter 8-Exception Handling/ Robust Programming

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

Page 21: Chapter 8-Exception Handling/ Robust Programming

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.

Page 22: Chapter 8-Exception Handling/ Robust Programming

Throwing/creating exceptions

Page 23: Chapter 8-Exception Handling/ Robust Programming

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 don’t get them confused with pre-defined ones).

Inherit from the Exception or Throwable class.

Quite often the exception classes are pretty empty.

Page 24: Chapter 8-Exception Handling/ Robust Programming

Exception class creationpublic class DivideByZeroException

extends Exception{

public DivideByZeroException(){

super(“Division by zero.”);}

public DivideByZeroException(String message)

{super(message);

}}

Page 25: Chapter 8-Exception Handling/ Robust Programming

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.

Page 26: Chapter 8-Exception Handling/ Robust Programming

throwingif(<error condition>)

throw new <AppropriateException>();or

throw new <AppropriateException>(String);

if(denominator == 0)throw new DivideByZeroException();

orthrow new DivideByZeroException(

“Division by zero!”);

Page 27: Chapter 8-Exception Handling/ Robust Programming

Alternate way of creating exceptions and throwing.if(denominator == 0){

DivideByZeroException e =new DivideByZeroException();

throw e;}

Page 28: Chapter 8-Exception Handling/ Robust Programming

Re-throwing exceptions

If we catch an exception and can’t completely deal with it, we want to re-throw the exception.

Page 29: Chapter 8-Exception Handling/ Robust Programming

Re-throwing exampletry{

//some code that might produce//a DivideByZeroException

}catch(DivideByZeroException ex){

//do some processing.//can’t completely deal with it though.throw ex;

}

Page 30: Chapter 8-Exception Handling/ Robust Programming

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.

Page 31: Chapter 8-Exception Handling/ Robust Programming

Advertising exceptions

public void method1() throws SomeException{…}

public double division(double num, double den)throws DivideByZeroException

{…}

Page 32: Chapter 8-Exception Handling/ Robust Programming

Guiding principles on exception handling

Page 33: Chapter 8-Exception Handling/ Robust Programming

Never squelch an exceptiontry{

//some code that might produce an// Exception

}catch(Exception e) //catch all exceptions{}

Page 34: Chapter 8-Exception Handling/ Robust Programming

Handling in moderation. Exception handling is a bit of a balancing act. You don’t want to handle all exceptions

yourself, as sometimes you don’t 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.

Page 35: Chapter 8-Exception Handling/ Robust Programming

Exceptions you don’t usually worry about Errors (NoSuchMethod, OutOfMemory) Don’t usually need to catch

ArrayIndexOutOfBounds exceptions, except in this next homework.

Page 36: Chapter 8-Exception Handling/ Robust Programming

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.

Page 37: Chapter 8-Exception Handling/ Robust Programming

Exception Handling Review

Page 38: Chapter 8-Exception Handling/ Robust Programming

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?

Page 39: Chapter 8-Exception Handling/ Robust Programming

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?

Page 40: Chapter 8-Exception Handling/ Robust Programming

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);

Page 41: Chapter 8-Exception Handling/ Robust Programming

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.println(“The answer:”+otherNum);

Page 42: Chapter 8-Exception Handling/ Robust Programming

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.

Page 43: Chapter 8-Exception Handling/ Robust Programming

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?