Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8-Exception Handling/ Robust Programming.

Similar presentations


Presentation on theme: "Chapter 8-Exception Handling/ Robust Programming."— Presentation transcript:

1 Chapter 8-Exception Handling/ Robust Programming

2 Overview n What is Exception Handling/Robust Programming. n Exception Handling in Java. n Trying/catching exceptions. n Creating/throwing exceptions. n Guiding principles of exception handling. n 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? n 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.

5 Robust programming n 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. n We have been programming for the general case. Once that works, program for the exceptional case.

6 Robust Programming Principles n 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. n You should always at least allow the user to save their work before crashing!

7 Detecting Errors n 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 n When a method detects an error, an error message called an exception is created and thrown to the methods that called the current method. n 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. n 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 n I need a few volunteers.

11 Trying and catching exceptions

12 How to catch an exception n 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. n We put the code that may produce an exception in a try block. n 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 n 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.

15 Catch details n You specify what kind of exception you are catching. –IOException –NumberFormatException –etc. n If you are not able to completely deal with the exception, do what you can and then re-throw it. n 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. n Put them in order from the most specific to the least specific. n First one that matches will be executed. n Remember about inheritance. Every exception class tends to inherit from Exception. So every exception will be of type Exception.

18 Finally n There is an extra block that we can have that will be performed whether an exception happens or not. It is called finally. n 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 n 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 n 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). n Inherit from the Exception or Throwable class. n Quite often the exception classes are pretty empty.

24 Exception class creation public class DivideByZeroException extends Exception { public DivideByZeroException() { super(“Division by zero.”); } public DivideByZeroException( String message) { super(message); }

25 Detecting and throwing exceptions n 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. n We use the throw command, and we throw some sort of exception object.

26 throwing if( ) throw new (); or throw new (String); if(denominator == 0) throw new DivideByZeroException(); or throw 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 n If we catch an exception and can’t completely deal with it, we want to re- throw the exception.

29 Re-throwing example try { //some code that might produce //a DivideByZeroException } catch(DivideByZeroException ex) { //do some processing. //can’t completely deal with it though. throw ex; }

30 Throwing in public n 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. n 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. n Exception handling is a bit of a balancing act. n 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. n 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 don’t usually worry about n Errors (NoSuchMethod, OutOfMemory) n Don’t usually need to catch ArrayIndexOutOfBounds exceptions, except in this next homework.

36 When not to use exception handling. n If you can detect an error before it is going to occur, do it. It will save your program time. n 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 n When you first encounter an error, what is the first thing that you should try to do? n What is the least that you should do when you encounter an unrecoverable error?

39 Exception Handling review. n What word do we use if we think some code might not execute correctly or might result in an exception? n How do we receive an exception that might be produced in some code?

40 Exception Handling review n 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 n 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);

42 Exception Handling Review n Create a new exception class called HalloweenException. n Write some code to create and throw a HalloweenException. n 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 n 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?


Download ppt "Chapter 8-Exception Handling/ Robust Programming."

Similar presentations


Ads by Google