Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Exceptions and bug handling Peter Wad Sackett.

Similar presentations


Presentation on theme: "Python Exceptions and bug handling Peter Wad Sackett."— Presentation transcript:

1 Python Exceptions and bug handling Peter Wad Sackett

2 2DTU 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.

3 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

4 4DTU Systems Biology, Technical University of Denmark Exception structure 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 The try-except structure of error handling

5 5DTU 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

6 6DTU 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 ?

7 7DTU 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.”)

8 8DTU 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.

9 9DTU 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 123.34 547.22 End of file

10 10DTU 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

11 11DTU 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

12 12DTU Systems Biology, Technical University of Denmark Formatting stings 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


Download ppt "Python Exceptions and bug handling Peter Wad Sackett."

Similar presentations


Ads by Google