Chapter 8-Exception Handling/ Robust Programming.

Slides:



Advertisements
Similar presentations
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Advertisements

Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
COMP 121 Week 5: Exceptions and Exception Handling.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Understand Error Handling Software Development Fundamentals LESSON 1.4.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch Announcements l Project 6 now out. »Milestone due Oct. 24th »Final project.
Chapter 81 Exception Handling Chapter 8. 2 Reminders Project 5 due Oct 10:30 pm Project 3 regrades due by midnight tonight Discussion groups now.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming: Guided Learning with Early Objects
Exceptions Handling Exceptionally Sticky Problems.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
COMP Exception Handling Yi Hong June 10, 2015.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Generics, Exceptions and Undo Command
Exceptions: When things go wrong
Why exception handling in C++?
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exception Handling Chapter 9 Edited by JJ.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Presentation transcript:

Chapter 8-Exception Handling/ Robust Programming

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.

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

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.

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.

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!

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.

Exception Handling in Java

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.

Exception handling example n I need a few volunteers.

Trying and catching exceptions

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.

Try/catch try { //code you want to try //may produce an exception } catch(Exception e) { //deal with the exception. }

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.

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.

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

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.

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.

finally try { //code to try } catch(Exception e) { //deal with exception } finally { //code you always want to run. }

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

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.

Throwing/creating exceptions

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.

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

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.

throwing if( ) throw new (); or throw new (String); if(denominator == 0) throw new DivideByZeroException(); or throw new DivideByZeroException( “Division by zero!”);

Alternate way of creating exceptions and throwing. if(denominator == 0) { DivideByZeroException e = new DivideByZeroException(); throw e; }

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

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

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.

Advertising exceptions public void method1() throws SomeException {…} public double division(double num, double den) throws DivideByZeroException {…}

Guiding principles on exception handling

Never squelch an exception try { //some code that might produce an // Exception } catch(Exception e)//catch all exceptions { }

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.

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.

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.

Exception Handling Review

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?

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?

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

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

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.

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?