Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See

Slides:



Advertisements
Similar presentations
Chapter 5 Errors Bjarne Stroustrup
Advertisements

Interfaces Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
Control Flow Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
COMP 121 Week 5: Exceptions and Exception Handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
Debugging Introduction to Computing Science and Programming I.
Nov 10, Fall 2006IAT 8001 Debugging. Nov 10, Fall 2006IAT 8002 How do I know my program is broken?  Compiler Errors –easy to fix!  Runtime Exceptions.
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.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
Exceptions COMPSCI 105 S Principles of Computer Science.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
CIS 270—Application Development II Chapter 13—Exception Handling.
Functions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Python – May 17 Recap lab Multidimensional list Exceptions Commitment: quiz tomorrow.
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.
Fixtures Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
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?
VB.Net - Exceptions Copyright © Martin Schray
COMP Exception Handling Yi Hong June 10, 2015.
Introduction to Exception Handling and Defensive Programming.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
FT228/3 Web Development Error processing. Introduction READ Chapter 9 of Java Server Pages from O’reilly 2 nd Edition Need to be able to 1) Diagnose and.
Interface and Implementation Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
C# 5.0 Alex Davies 22 nd December What we will cover C# 5.0,.NET 4.5, Visual Studio 11 Caller Info Attributes Upgrade from synchronous to asynchronous.
Exception Handling. VB.NET has an inbuilt class that deals with errors. The Class is called Exception. When an exception error is found, an Exception.
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.
Python Aliasing Copyright © Software Carpentry 2010
Exceptions in Python Error Handling.
Exceptions.
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Introduction Exception handling Exception Handles errors
Creating and Modifying Text part 2
Exceptions and files Taken from notes by Dr. Neil Moore
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Exceptions and files Taken from notes by Dr. Neil Moore
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions 19-Feb-19.
Advanced Python Concepts: Exceptions
Exceptions 7-Apr-19.
Advanced Python Concepts: Exceptions
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Exception Handling COSC 1323.
CS 5010 Program Design Paradigms "Bootcamp" Lesson 12.1
Exceptions 5-Jul-19.
CMSC 202 Exceptions.
Presentation transcript:

Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See for more information. Testing

Exceptions Things go wrong

TestingExceptions Things go wrong External

TestingExceptions Things go wrong External –Missing or badly-formatted file

TestingExceptions Things go wrong External –Missing or badly-formatted file Internal

TestingExceptions Things go wrong External –Missing or badly-formatted file Internal –Bug in code

TestingExceptions Things go wrong External –Missing or badly-formatted file Internal –Bug in code

TestingExceptions Things go wrong External –Missing or badly-formatted file Internal –Bug in code Handling errors sensibly is easy

TestingExceptions Option #1: return status code

TestingExceptions Option #1: return status code params, status = read_params(param_file) if status != OK: log.error('Failed to read', param_file) sys.exit(ERROR) grid, status = read_grid(grid_file) if status != OK: log.error('Failed to read', grid_file) sys.exit(ERROR)

TestingExceptions Option #1: return status code This is what we really care about params, status = read_params(param_file) if status != OK: log.error('Failed to read', param_file) sys.exit(ERROR) grid, status = read_grid(grid_file) if status != OK: log.error('Failed to read', grid_file) sys.exit(ERROR)

TestingExceptions Option #1: return status code The rest is error handling params, status = read_params(param_file) if status != OK: log.error('Failed to read', param_file) sys.exit(ERROR) grid, status = read_grid(grid_file) if status != OK: log.error('Failed to read', grid_file) sys.exit(ERROR)

TestingExceptions Hard to see the forest for the trees

TestingExceptions Hard to see the forest for the trees Expected flow of control

TestingExceptions Hard to see the forest for the trees Expected flow of control Error handling

TestingExceptions Hard to see the forest for the trees Expected flow of control Error handling So people don't even try to handle errors

TestingExceptions Hard to see the forest for the trees Expected flow of control Error handling So people don't even try to handle errors Which makes them harder to find and fix when they do occur

TestingExceptions Option #2: use exceptions

TestingExceptions Option #2: use exceptions Separate "normal" operation from code that handles "exceptional" cases

TestingExceptions Option #2: use exceptions Separate "normal" operation from code that handles "exceptional" cases Make both easier to understand

TestingExceptions Rearrange this... params, status = read_params(param_file) if status != OK: log.error('Failed to read', param_file) sys.exit(ERROR) grid, status = read_grid(grid_file) if status != OK: log.error('Failed to read', grid_file) sys.exit(ERROR)

TestingExceptions...to put "normal" code in one place... params, status = read_params(param_file) if status != OK: log.error('Failed to read', param_file) sys.exit(ERROR) grid, status = read_grid(grid_file) if status != OK: log.error('Failed to read', grid_file) sys.exit(ERROR) params = read_params(param_file) grid = read_grid(grid_file)

TestingExceptions...and error handling code in another params, status = read_params(param_file) if status != OK: log.error('Failed to read', param_file) sys.exit(ERROR) grid, status = read_grid(grid_file) if status != OK: log.error('Failed to read', grid_file) sys.exit(ERROR) params = read_params(param_file) grid = read_grid(grid_file) log.error('Failed to read', filename) sys.exit(ERROR)

TestingExceptions...and error handling code in another params, status = read_params(param_file) if status != OK: log.error('Failed to read', param_file) sys.exit(ERROR) grid, status = read_grid(grid_file) if status != OK: log.error('Failed to read', grid_file) sys.exit(ERROR) Only need one copy of the error handling code params = read_params(param_file) grid = read_grid(grid_file) log.error('Failed to read', filename) sys.exit(ERROR)

TestingExceptions Join the two parts with try and except params, status = read_params(param_file) if status != OK: log.error('Failed to read', param_file) sys.exit(ERROR) grid, status = read_grid(grid_file) if status != OK: log.error('Failed to read', grid_file) sys.exit(ERROR) try: params = read_params(param_file) grid = read_grid(grid_file) except: log.error('Failed to read', filename) sys.exit(ERROR)

TestingExceptions You have seen exceptions before

TestingExceptions You have seen exceptions before >>> open('nonexistent.txt', 'r') IOError: No such file or directory: 'nonexistent.txt'

TestingExceptions You have seen exceptions before >>> open('nonexistent.txt', 'r') IOError: No such file or directory: 'nonexistent.txt' >>> values = [0, 1, 2] >>> values[99] IndexError: list index out of range

TestingExceptions Use try and except to deal with them yourself

TestingExceptions Use try and except to deal with them yourself >>> try:... reader = open('nonexistent.txt', 'r')... except IOError:... print 'Whoops!' Whoops!

TestingExceptions Use try and except to deal with them yourself >>> try:... reader = open('nonexistent.txt', 'r')... except IOError:... print 'Whoops!' Whoops! Blue indicates regular output

TestingExceptions Use try and except to deal with them yourself >>> try:... reader = open('nonexistent.txt', 'r')... except IOError:... print 'Whoops!' Whoops! Try to do this...

TestingExceptions Use try and except to deal with them yourself >>> try:... reader = open('nonexistent.txt', 'r')... except IOError:... print 'Whoops!' Whoops!...and do this if an IO error occurs

TestingExceptions Use try and except to deal with them yourself...and do this if an IO error occurs 'IOError' is how Python reports 'file not found' >>> try:... reader = open('nonexistent.txt', 'r')... except IOError:... print 'Whoops!' Whoops!

TestingExceptions Can put many lines of code in a try block

TestingExceptions Can put many lines of code in a try block And handle several errors afterward

TestingExceptions Can put many lines of code in a try block And handle several errors afterward try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError: log_error_and_exit('IO error') except ArithmeticError: log_error_and_exit('Arithmetic error')

TestingExceptions Try to do this try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError: log_error_and_exit('IO error') except ArithmeticError: log_error_and_exit('Arithmetic error') Can put many lines of code in a try block And handle several errors afterward

TestingExceptions try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError: log_error_and_exit('IO error') except ArithmeticError: log_error_and_exit('Arithmetic error') Handle I/O errors here Can put many lines of code in a try block And handle several errors afterward

TestingExceptions try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError: log_error_and_exit('IO error') except ArithmeticError: log_error_and_exit('Arithmetic error') and numerical errors here Can put many lines of code in a try block And handle several errors afterward

TestingExceptions try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError: log_error_and_exit('IO error') except ArithmeticError: log_error_and_exit('Arithmetic error') These messages aren't very helpful Can put many lines of code in a try block And handle several errors afterward

TestingExceptions Python 2.6 try: x = 1/0 except Exception, error: print error

TestingExceptions Python 2.6 try: x = 1/0 except Exception, error: print error Stores information about what went wrong

TestingExceptions Python 2.6 try: x = 1/0 except Exception, error: print error Stores information about what went wrong Different information for different kinds of errors

TestingExceptions Python 2.6 try: x = 1/0 except Exception, error: print error Python 2.7 try: x = 1/0 except Exception as error: print error More readable

TestingExceptions Better error messages

TestingExceptions try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError as err: log_error_and_exit('Cannot read/write' + err.filename) except ArithmeticError as err: log_error_and_exit(err.message) Better error messages

TestingExceptions try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError as err: log_error_and_exit('Cannot read/write' + err.filename) except ArithmeticError as err: log_error_and_exit(err.message) Better error messages

TestingExceptions try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError as err: log_error_and_exit('Cannot read/write' + err.filename) except ArithmeticError as err: log_error_and_exit(err.message) Better error messages Help user figure out which file

TestingExceptions try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError as err: log_error_and_exit('Cannot read/write' + err.filename) except ArithmeticError as err: log_error_and_exit(err.message) Better error messages No worse than the default

TestingExceptions A question of style

TestingExceptions A question of style try: grid = read_grid(grid_file) except IOError: grid = default_grid()

TestingExceptions A question of style if file_exists(grid_file): grid = read_grid(grid_file) else: grid = default_grid() try: grid = read_grid(grid_file) except IOError: grid = default_grid()

TestingExceptions try: grid = read_grid(grid_file) except IOError: grid = default_grid() A question of style if file_exists(grid_file): grid = read_grid(grid_file) else: grid = default_grid() Use exceptions for exceptional cases

TestingExceptions Another question of style

TestingExceptions Another question of style But first...

TestingExceptions Exceptions can be thrown a long way

TestingExceptions try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError as err: log_error_and_exit('Cannot read/write' + err.filename) except ArithmeticError as err: log_error_and_exit(err.message) Exceptions can be thrown a long way

TestingExceptions try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError as err: log_error_and_exit('Cannot read/write' + err.filename) except ArithmeticError as err: log_error_and_exit(err.message) These are function calls Exceptions can be thrown a long way

TestingExceptions Any errors they don't catch... Exceptions can be thrown a long way try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError as err: log_error_and_exit('Cannot read/write' + err.filename) except ArithmeticError as err: log_error_and_exit(err.message)

TestingExceptions Exceptions can be thrown a long way try: params = read_params(param_file) grid = read_grid(grid_file) entropy = lee_entropy(params, grid) write_entropy(entropy_file, entropy) except IOError as err: log_error_and_exit('Cannot read/write' + err.filename) except ArithmeticError as err: log_error_and_exit(err.message)...are caught and handled here

TestingExceptions "Throw low, catch high"

TestingExceptions "Throw low, catch high" Many places where errors might occur

TestingExceptions "Throw low, catch high" Many places where errors might occur Only a few where they can sensibly be handled

TestingExceptions "Throw low, catch high" Many places where errors might occur Only a few where they can sensibly be handled A linear algebra library doesn't know how its callers will want to report errors...

TestingExceptions "Throw low, catch high" Many places where errors might occur Only a few where they can sensibly be handled A linear algebra library doesn't know how its callers will want to report errors......so it shouldn't try to handle them itself

TestingExceptions You can raise exceptions yourself

TestingExceptions You can raise exceptions yourself should

TestingExceptions You can raise exceptions yourself should def read_grid(grid_file): '''Read grid, checking consistency.''' data = read_raw_data(grid_file) if not grid_consistent(data): raise Exception('Inconsistent grid: ' + grid_file) result = normalize_grid(data) return result

TestingExceptions You can raise exceptions yourself should def read_grid(grid_file): '''Read grid, checking consistency.''' data = read_raw_data(grid_file) if not grid_consistent(data): raise Exception('Inconsistent grid: ' + grid_file) result = normalize_grid(data) return result

TestingExceptions You can define new types of exceptions too

TestingExceptions You can define new types of exceptions too should

TestingExceptions You can define new types of exceptions too should Need to understand classes and objects first

July 2010 created by Greg Wilson Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See for more information.