Python Exceptions and bug handling Peter Wad Sackett.

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
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.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Exceptions COMPSCI 105 S Principles of Computer Science.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Chapter 12: Exception Handling
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
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.
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?
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions and Assertions Chapter 15 – CSCI 1302.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Firoze Abdur Rakib. Syntax errors, also known as parsing errors, are perhaps the most common kind of error you encounter while you are still learning.
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
Python Built-in Exceptions Data Fusion Albert Esterline Source:
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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 Lists and Sequences Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark List properties What are lists? A list is a mutable.
Python Simple file reading Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Simple Pythonic file reading Python has a special.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Exceptions in Python Error Handling.
Handling errors try except
Exceptions and files Taken from notes by Dr. Neil Moore
Python’s Errors and Exceptions
Exceptions and files Taken from notes by Dr. Neil Moore
Python Stateful Parsing
Part B – Structured Exception Handling
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Exceptions.
15-110: Principles of Computing
Problems Debugging is fine and dandy, but remember we divided problems into compile-time problems and runtime problems? Debugging only copes with the former.
Advanced Python Concepts: Exceptions
Advanced Python Concepts: Exceptions
By Ryan Christen Errors and Exceptions.
Exception Handling COSC 1323.
Exception Handling.
Python Exceptions and bug handling
Python Simple file reading
IST256 : Applications Programming for Information Systems
Presentation transcript:

Python Exceptions and bug handling Peter Wad Sackett

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.

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

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

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

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 ?

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

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.

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 End of file

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

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

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( ) Time with leading zeroes ”{:02d}:{:02d}:{:02d}”.format(1, 2, 30) There is much more to format than this