Download presentation
Presentation is loading. Please wait.
1
Python Exceptions and bug handling
Peter Wad Sackett
2
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.
3
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. Some of the more important are: IndexError sequence subscript out of range KeyError dictionary key not found ZeroDivisionError division by 0 ValueError value is inappropiate for the built-in function TypeError function or operation using the wrong type IOError input/output error, file handling
4
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
5
Examples 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
6
Examples How to catch bad input 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) What happens if there is no sys.exit ? What is the scope of my_number ?
7
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 meaningful 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.”)
8
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.
9
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( ) Time with leading zeroes ”{:02d}:{:02d}:{:02d}”.format(1, 2, 30) There is much more to format than this
10
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.