Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?

Slides:



Advertisements
Similar presentations
Chapter 5 Errors Bjarne Stroustrup
Advertisements

11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
Annoucements  Next labs 9 and 10 are paired for everyone. So don’t miss the lab.  There is a review session for the quiz on Monday, November 4, at 8:00.
1 Week 11 l Basic Exception Handling »the mechanics of exceptions l Defining and Using Exceptions »some "simple" cases l Reality Check »guidelines for.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Debugging Introduction to Computing Science and Programming I.
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 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
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.
1 Functional Testing Motivation Example Basic Methods Timing: 30 minutes.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Exceptions COMPSCI 105 S Principles of Computer Science.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
ICAPRG301A Week 4Buggy Programming ICAPRG301A Apply introductory programming techniques Program Bugs US Navy Admiral Grace Hopper is often credited with.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
General Programming Introduction to Computing Science and Programming I.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Testing Michael Ernst CSE 140 University of Washington.
Testing CSE 140 University of Washington 1. Testing Programming to analyze data is powerful It’s useless if the results are not correct Correctness is.
Introduction to Exception Handling and Defensive Programming.
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Error messages 25-Apr-17.
Exceptions CMSC 201. Overview Exceptions are run-time errors, especially ones that the programmer cannot predict.  example 1: division by zero  example.
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.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Testing CSE 160 University of Washington 1. Testing Programming to analyze data is powerful It’s useless (or worse!) if the results are not correct Correctness.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Introduction to Exceptions in Java CS201, SW Development Methods.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
Exceptions in Python Error Handling.
Introduction to Computing Science and Programming I
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Why exception handling in C++?
Testing UW CSE 160 Winter 2017.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Topics Introduction to File Input and Output
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Exceptions & Error Handling
Testing UW CSE 160 Winter 2016.
CSC 143 Error Handling Kinds of errors: invalid input vs programming bugs How to handle: Bugs: use assert to trap during testing Bad data: should never.
Exceptions.
Exceptions 19-Feb-19.
Problems Debugging is fine and dandy, but remember we divided problems into compile-time problems and runtime problems? Debugging only copes with the former.
Exceptions 7-Apr-19.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
CSC 143 Java Errors and Exceptions.
Additional control structures
Exceptions 10-May-19.
Computer Science 340 Software Design & Testing
Topics Introduction to File Input and Output
Exceptions 5-Jul-19.
Presentation transcript:

Errors And How to Handle Them

GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming? Answer: Both. Here’s what you want: Can you do it?

Errors and exceptions Your program isn’t alone in the universe—it has to interact with things outside itself Users typing things in Data read from files Calls to your functions from “the outside world” Your calls to “someone else’s” functions It helps to think in terms of “my code” and “not my code” An error is a mistake in your code, and it’s your fault An exception is a mistake that isn’t in your code, and isn’t your fault, but that doesn’t mean you can ignore it This isn’t entirely accurate, and the distinction isn’t really all that clear, but it’s a reasonable simplification

Sanity checking While Python has some built-in features for dealing with various kinds of mistakes, there are some simple things you can do without them Sanity checking is simply testing whether values are reasonable age = int(input("What is your age? ")) if age 120: print("No you're not!")

Errors An error is a bug in your code—fix it! There is no real substitute for careful testing, but when errors do occur— Putting in print statements (and later removing them, when the code works) is generally the most helpful Using the debugger to step through your code is sometimes helpful assert statements (covered next) can, on rare occasions, be helpful Other suggestions— Take a break—do something else for a while Explain your code to a friend They don’t have to understand you, but they should pretend to listen If you have no friends, explain your code to your dog, or to your teddy bear Not to your cat—they really don’t listen

Executable documentation Comments are useful to the human reader, but ignored by the computer Assertions are useful to the human reader, and their validity can be checked by the computer Unfortunately, assertions are limited to statements that can be expressed by a boolean expression Syntax: assert boolean_expression or assert boolean_expression, message If the boolean expression is False, an AssertionError occurs The primary purpose of the assert statement is to inform the human reader that the following code can assume the assertion is true The message is hardly every required, but if used, should provide additional information Another purpose of the assert statement is to tell you when you are mistaken, and contrary to your expectations, the boolean expression is False

assert and require Some languages have both “assert” and “require” assert boolean_expression says that, at this point in the code, I believe the boolean_expression to be True require boolean_expression says that, in order for the following code to work correctly, the boolean_expression must be True Python has only assert, but since “assert” and “require” do essentially the same thing (signal that an error has occurred), we can implement “require” using assert def require(b): assert b, "Requirement not met.” Or we can simply use assert to mean require

Example def first_asterisk(s): """Returns the index of the first '*' in a string.""" require('*' in s) for index in range(0, len(s)): if s[index] == '*': break assert s[index] == '*' assert '*' not in s[:index] return index This is excessive, and I don’t recommend it as a general practice, but the occasional use of assert can be helpful

Someone else’s problem An exception is a mistake that you can detect, but not a bug you can fix It is “someone else’s problem” Later in the course we will talk about classes, and the phrase “someone else” will mean “some other class” When you detect such a mistake, you should raise (or throw) an exception Syntax: raise name_of_exception(message) The most general type of exception has the name Exception, so usually you would just say raise Exception(message) Used correctly, raising an exception immediately exits the function that it is in

Square root example def square_root(n): “””Finds the square root of a non-negative number.””” if n epsilon: guess = (guess + quotient) / 2 quotient = n / guess return guess Raising the exception says to the caller, “You’re doing it wrong!”

Flow of control When an exception is raised, the usual flow of control is disrupted The exception must be caught We will talk about how to do this shortly Here’s what happens when a function throws an exception: Control immediately returns to the function that called this one If that function catches the exception, it executes whatever code is necessary to deal with the situation If the function does not catch the exception, it returns to the function that called it, and so on up the line If no function ever catches the exception, the program terminates with an error message In other words, the exception “propagates up the call chain” until it is caught, or the system catches it and terminates the program Exceptions are for dealing with errors, not for routine flow of control

Catching exceptions Syntax: try: code that might result in an exception except type_of_exception_1: code to do something when exception 1 occurs except type_of_exception_2: code to do something when exception 2 occurs finally: code to be performed whether or not an exception occurred You may have as many except clauses as you like except and finally are both optional, but you must have at least one Semantics: The code in the try part is executed If an exception occurs, the first except clause of the right type is executed If no except clause is of the right type, control goes to the calling function To catch any type of exception, say except Exception : The finally clause is executed, whether or not an exception occurred

Reading in an integer def get_int(prompt): “””Gets an integer from the user””” try: age = int(input(prompt)) return age except ValueError: print("That's not an integer!") return get_int(prompt) >>> get_int("What is your age? ") What is your age? fh That's not an integer! What is your age? dgghdf That's not an integer! What is your age? (result printed by IDLE)

Getting the message try: root = square_root(-5) except Exception as msg: print(msg) square_root called with -5 If the exception occurs and you don’t catch it, the program will crash and the system will print out the message >>> square_root(-5) Traceback (most recent call last): File " ", line 1, in square_root(-5) File "/Users/dave/Box Sync/Programming/Python3_programs/scratch.py", line 34, in square_root raise Exception("square_root called with " + str(n)) Exception: square_root called with -5

assert or raise ? When an assert statement fails, it raises an AssertionError, which is a kind of Exception Hence, the following two things are almost exactly equivalent: assert boolean_expression, message if not boolean_expression: raise AssertionError(message) So when do you use which? You should assert things which you really expect to be true; and if they aren’t, you should fix your code so that they are When your function gets invalid data (provided by “someone else”) you should raise an exception, thus making it “their problem”

The End “Never test for an error condition you don’t know how to handle.” - Steinbach's Guideline for Systems Programming