Exceptions and Bug Handling

Download Report

Transcript Exceptions and Bug Handling

Python
Exceptions and bug handling
Peter Wad Sackett
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.
2
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 range
KeyError
dictionary key not found
ZeroDivisionError division by 0
3
ValueError
value is inappropiate for the built-in function
TypeError
function or operation using the wrong type
IOError
input/output error, file handling
DTU Systems Biology, Technical University of Denmark
Exception structure
The try-except structure of error handling
try:
normal statements which may fail
except exception-type:
error handling statements for this specific exception
except (exception-type1, exception-type2):
error handling statements for these specific exceptions
except exception-type as errname:
error handling statements for this specific exception getting instance via errname
except:
general error handling statements catching all exception types
else:
statements executed if no exception
finally:
clean-up statements always executed
4
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, end=’’)
infile.close
5
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 ?
6
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.”)
7
DTU Systems Biology, Technical University of Denmark
Assertions
Assertions are for debugging – not errors.
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 as err:
print(str(err))
You can ignore assertions by running Python with –O option.
8
DTU Systems Biology, Technical University of Denmark
Formatting strings
Converting to upper/lower case
mystring = ’AbCdEfG’
print(mystring.lower(), mystring.upper())
result: abcdefg ABCDEFG
Formatting 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 this
https://docs.python.org/3.5/library/string.html
9
DTU Systems Biology, Technical University of Denmark
Comparing series of values
Many languages can only compare a variable with a value in
separate comparisons, like just below.
answer = ’yes’
if answer == ’yes’ or answer == ’maybe’:
# Have a party
If a variable has a number of ”good” options it can take, then
you can set up a list it will be compared with, using in.
number = int(input(”Gimme a number ”))
if number in (1, 3, 5, 7, 9):
print(”Yay, we got an uneven number below 10”)
else:
print(”No good number”)
The operator opposite in, is not in:
if codon not in (’TGA’, ’TAA’, ’TAG’):
This naturally also works with strings as seen above.
10
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.
Green
ATCGTCGATGCATCGATCGATCATCGATCGTGATAGCTACGTACGT
ACTACGTCAGTCATGCTCTGTCGTACGCATGATAGCTCGTACGTCG
GTAGACCGCTACGATGCACCACACAGCGCGAATACTAGC
Red
As can be seen the sequence is between the green and the red line.
Some number data
12
3.34
54
7.22
End of file
11
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:
if flag == True:
if line is red:
12
flag = True
data += line
flag = False
DTU Systems Biology, Technical University of Denmark
Stateful parsing 3
Real code example
# 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.
13
DTU Systems Biology, Technical University of Denmark