12
Python Exceptions and bug handling Peter Wad Sackett

Python Exceptions and bug handling Peter Wad Sackett

Embed Size (px)

DESCRIPTION

3DTU Systems Biology, Technical University of Denmark Some exceptions The full list of exceptions is regrettably big. The exceptions also have a hierarchy. Some are special cases of general error, e.g. IndexError and KeyError are special cases of LookupError. https://docs.python.org/3/library/exceptions.html Some of the more important are: IndexErrorsequence subscript out of range KeyErrordictionary key not found ZeroDivisionErrordivision by 0 ValueErrorvalue is inappropiate for the built-in function TypeErrorfunction or operation using the wrong type IOErrorinput/output error, file handling

Citation preview

Page 1: Python Exceptions and bug handling Peter Wad Sackett

PythonExceptions and bug handling

Peter Wad Sackett

Page 2: Python Exceptions and bug handling Peter Wad Sackett

2 DTU Systems Biology, Technical University of Denmark

Exception handling

What are these exceptions??

Official explanation: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

So ... it is an unexpected event, like an error. However, not all exceptions are errors.When an error occurs an exception is raised.When an exception occurs python stops whatever it is doing and goes to the last seen exception handler.There is always the top/main exception handler. That is the one that gives you the well-known stack trace, which you see every time you make an error.You can raise exceptions yourself in the code.You can create your own exceptions.When an exception is handled the program can continue.

Page 3: Python Exceptions and bug handling Peter Wad Sackett

3 DTU Systems Biology, Technical University of Denmark

Some exceptions

The full list of exceptions is regrettably big.The exceptions also have a hierarchy. Some are special cases of general error, e.g. IndexError and KeyError are special cases of LookupError.https://docs.python.org/3/library/exceptions.html

Some of the more important are:IndexError sequence subscript out of rangeKeyError dictionary key not foundZeroDivisionError division by 0ValueError value is inappropiate for the built-in functionTypeError function or operation using the wrong typeIOError input/output error, file handling

Page 4: Python Exceptions and bug handling Peter Wad Sackett

4 DTU Systems Biology, Technical University of Denmark

Exception structure

try: normal statements which may failexcept exception-type: error handling statements for this specific exceptionexcept (exception-type1, exception-type2): error handling statements for these specific exceptionsexcept exception-type as errname: error handling statements for this specific exception getting instance via errnameexcept: general error handling statements catching all exception typeselse: statements executed if no exceptionfinally: clean-up statements always executed

The try-except structure of error handling

Page 5: Python Exceptions and bug handling Peter Wad Sackett

5 DTU Systems Biology, Technical University of Denmark

I/O exception example

How to catch file opening errors

import sys

try:

infile = open(’myfile.txt’, ’r’)

except IOError as error:

print(”Can’t open file, reason:”, str(error))

sys.exit(1)

for line in infile:

print line

infile.close

Page 6: Python Exceptions and bug handling Peter Wad Sackett

6 DTU Systems Biology, Technical University of Denmark

Keyboard input exception example

How to catch bad input from keyboard

import sys

try:

my_number = int(input(”Please, input an integer”))

except ValueError:

print(”You did not enter an integer”)

sys.exit(1)

print(”The number was”, my_number)

Scope of my_number………What happens if there is no sys.exit ?

Page 7: Python Exceptions and bug handling Peter Wad Sackett

7 DTU Systems Biology, Technical University of Denmark

Raising an exception

It can be useful to raise exceptions yourself. You can create code that checks for errors that are not programatically wrong, but are still errors in your program.You don’t need try to raise an exception, but then the top level exception handler will handle it.try:

number = int(input(”Enter a number, but not 10: ”))

if number == 10:

raise ValueError(”Oh no, not 10”)

except ValueError as error:

print(”The exception is:”, str(error))

else:

print(”Good job”)

print(”Business as usual, this will be executed.”)

Page 8: Python Exceptions and bug handling Peter Wad Sackett

8 DTU Systems Biology, Technical University of Denmark

Assertions

Assertions are for debugging.An assertion is conditionally rasing an exception; AssertionError.You can choose to catch it or not, inside a try or not.import sys

try:

number = int(input(”Please input a small positive number:”))

assert number > 0 and number < 10, ”Number out of range”

except ValueError:

print(”You don’t know what a number is”)

sys.exit(1)

except AssertionError:

print(”Not a small number”)

You can ignore assertions by running Python with –O option.

Page 9: Python Exceptions and bug handling Peter Wad Sackett

9 DTU Systems Biology, Technical University of Denmark

Stateful parsing 1

Imagine a file with this content

I am a data file.Some of my lines don’t matter to you.Other lines contain data you want to extract, like DNA sequence.These data span several lines.The lines with the data can be identified by a specific pattern.GreenATCGTCGATGCATCGATCGATCATCGATCGTGATAGCTACGTACGTACTACGTCAGTCATGCTCTGTCGTACGCATGATAGCTCGTACGTCGGTAGACCGCTACGATGCACCACACAGCGCGAATACTAGCRedAs can be seen the sequence is between the green and the red line.Some number data12 3.3454 7.22End of file

Page 10: Python Exceptions and bug handling Peter Wad Sackett

10 DTU Systems Biology, Technical University of Denmark

Stateful parsing 2

Stateful parsing is reading a file line by line with the intention of collecting some data from the file by observing a state.The state is cheked by a flag (variable) which is either True or False. The flag is initially False, denoting that we have not seen the green line, which tells us that the data comes now. When we see/pass the green line the flag is set to True. It is now time to collect the data. When we pass the red line the flag is set back to False indicating no more data.

Here is some pseudo code for the process:(data, flag) = (’’, False)for line in file: if line is green: flag = True if flag == True:data += line if line is red: flag = False

Page 11: Python Exceptions and bug handling Peter Wad Sackett

11 DTU Systems Biology, Technical University of Denmark

Stateful parsing 3

# statements opening a file(data, seqflag) = (’’, False)for line in file: if line == ”Red\n”: seqflag = False if seqflag: data += line[:-1] if line == ”Green\n”: seqflag = True

if seqflag: raise ValueError(”Format is not right. Can’t trust result”)# Statements closing file

By changing the order of the 3 if’s, the green line and/or the red line will be considered as part of the collected data or not.

Real code example

Page 12: Python Exceptions and bug handling Peter Wad Sackett

12 DTU Systems Biology, Technical University of Denmark

Formatting stings

Converting to upper/lower casemystring = ’AbCdEfG’

print(mystring.lower(), mystring.upper)

result: abcdefg ABCDEFGFormatting a string with positional arguments”Hello {0}, your number is {1}”.format(’Peter’, 42)

Floating point number with rounding to 3 decimals”{0:.3f}”.format(234.56789)

Time with leading zeroes”{:02d}:{:02d}:{:02d}”.format(1, 2, 30)

There is much more to format than thishttps://docs.python.org/3.5/library/string.html