Errors. And How to Handle Them

Similar documents
CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Errors and Exceptions

Assertions, pre/postconditions

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Exceptions in Java

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Text Input and Conditionals

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Introduction to Computer Programming for Non-Majors

Python for Informatics

Introduction to Computer Programming for Non-Majors

Selection the If Statement Try Catch and Validation

COMP1730/COMP6730 Programming for Scientists. Testing and Debugging.

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

CS 3 Introduction to Software Engineering. 3: Exceptions

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Chapter 5 Errors. Bjarne Stroustrup

Testing. UW CSE 160 Winter 2016

Section 0.3 The Order of Operations

MITOCW watch?v=9h6muyzjms0

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Intro. Scheme Basics. scm> 5 5. scm>

CSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray

APPENDIX B. Fortran Hints

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

Lecture 9: July 14, How to Think About Debugging

Decisions, Decisions. Testing, testing C H A P T E R 7

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Internal Classes and Exceptions

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming

Introduction to: Computers & Programming: Exception Handling

Divisibility Rules and Their Explanations

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

Introduction to Computer Programming for Non-Majors

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

Classes, interfaces, & documentation. Review of basic building blocks

CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

An Introduction to Python

Repetition Through Recursion

n Specifying what each method does q Specify it in a comment before method's header n Precondition q Caller obligation n Postcondition

CSE 331 Software Design & Implementation

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Control Structures 1 / 17

Pupil Name. Year. Teacher. Target Level. Key Stage 3 Self-Assessment Year 9 Python. Spelling Test No 3. Spelling Test No 2. Spelling Test No 1

The Big Python Guide

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

(Python) Chapter 3: Repetition

Chapter 9: Dealing with Errors

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

These are notes for the third lecture; if statements and loops.

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute.

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Designing Robust Classes

Testing and Debugging

Racket Style Guide Fall 2017

a correct statement? You need to know what the statement is supposed to do.

Python Programming: An Introduction to Computer Science

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

CS112 Lecture: Exceptions and Assertions

Flow Control: Branches and loops

Error Handling in C++

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Testing is a very big and important topic when it comes to software development. Testing has a number of aspects that need to be considered.

Zero-Knowledge Proofs. Zero-Knowledge Proofs. Slides from a Talk by Eric Postpischil

Slide Set 15 (Complete)

Assertions and Exceptions Lecture 11 Fall 2005

Introduction to Problem Solving and Programming in Python.

CMSC 201 Computer Science I for Majors

MicroSurvey Users: How to Report a Bug

Lecture 4 CSE July 1992

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Close Your File Template

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

Python Programming: An Introduction to Computer Science

ASCII Art. Introduction: Python

LOOPS. Repetition using the while statement

Exceptions CS GMU

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012

Chapter 5: Control Structures

Introduction to Computer Programming for Non-Majors

printf( Please enter another number: ); scanf( %d, &num2);

Software Testing Lecture 1. Justin Pearson

Introduction to Programming

3 Nonlocal Exit. Quiz Program Revisited

CATCH Me if You Can Doug Hennig

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Introduction to Python (All the Basic Stuff)

If Statements, For Loops, Functions

Transcription:

Errors And How to Handle Them 1

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? 2

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 3

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 < 3 or age > 120: print("no you're not!") 4

Errors An error is a bug in your code fix it! There is no 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 5

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 6

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 7

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 8

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 9

Square root example def square_root(n): Finds the square root of a non-negative number. if n < 0: raise Exception("square_root called with " + str(n)) epsilon = 0.0000001 guess = n / 2 quotient = n / guess while abs(quotient - guess) > epsilon: guess = (guess + quotient) / 2 quotient = n / guess return guess Raising the exception says to the caller, You re doing it wrong! 10

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 11

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 12

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? 99 99 (result printed by IDLE) 13

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 "<pyshell#42>", line 1, in <module> 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 14

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 15

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