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

Slides:



Advertisements
Similar presentations
Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein Classes and Objects Object Oriented Programming.
Advertisements

For loops Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas.
Python Basics: Statements Expressions Loops Strings Functions.
Introduction to Python
Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein Classes and Objects Object Oriented Programming.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
1 Exception-Handling Overview Exception: when something unforeseen happens and causes an error Exception handling – improves program clarity by removing.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
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.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Exceptions COMPSCI 105 S Principles of Computer Science.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
Introduction to Python
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.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
H3D API Training  Part 3.1: Python – Quick overview.
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?
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Built-in Data Structures in Python An Introduction.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Python Conditionals chapter 5
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
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:
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
Python Exceptions and bug handling Peter Wad Sackett.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Python: Exception Handling Damian Gordon. Exception Handling When an error occurs in a program that causes the program to crash, we call that an “exception”
Exceptions in Python Error Handling.
George Mason University
Introduction to Python
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Why exception handling in C++?
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Python’s Errors and Exceptions
Exceptions and files Taken from notes by Dr. Neil Moore
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Exceptions.
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
Python Syntax Errors and Exceptions
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Advanced Python Concepts: Exceptions
By Ryan Christen Errors and Exceptions.
Exception Handling COSC 1323.
Topics Introduction to File Input and Output
Exception Handling.
Dealing with Runtime Errors
Presentation transcript:

Exception Handling Genome 559

Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = myClass('student', 'teacher') 2) __str__() class function and how Python print works 3) Other core Python class functions - __add__()# used for the '+' operator __mul__()# used for the '*' operator __sub__()# used for the '-' operator etc.

Extending Classes Suppose you want to build on a class that Python (or someone else) has already written for you? get their code and copy it into your own file for modification OR use the “extension” mechanism provided for you by Python

Extension formalism – much like biological classification class Eukaryote class Animal (extends Eukaryote ) add class method movementRate() class Insecta (extends Animal ) add class method numberOfWings() class Drosophila (extends Animal ) add class method preferredFruit() Drosophila is an Insecta so it has all the Insecta data structures and methods. Drosophila is also an Animal so it has all the Animal data structures and methods (and Eukaryote, though we didn't define any). What methods are available for an object of type Drosophila ?

Writing a new Class by extension Writing a class (review): class Date: __init__(self, day, month, year): [assign arguments to class variables] Extending an existing class: class HotDate(Date): __init__(self, day, month, year, toothbrush): super(day, month, year) self.bringToothbrush = toothbrush ALL OF THE DATA TYPES AND METHODS WRITTEN FOR Date ARE AVAILABLE!! class to extend super - call the con- structor for Date

class Eukaryote class Animal (extends Eukaryote ) add class method movementRate() class Insecta (extends Animal ) add class method numberOfWings() class Drosophila (extends Animal ) add class method preferredFruit() super is Eukaryote super is Animal super is Insecta Class hierarchy

Exception Handling What if you want to enforce that a Date have integer values for day, month, and year? class Date: def __init__(self, day, month, year): self.day = day self.month = month self.year = year myDate = Date("Ides", "March", "IXIV") Does this work?

import sys intval = int(sys.argv[1]) import sys try: intval = int(sys.argv[1]) except: print “first argument must be parseable as an int value” sys.exit() How could you check that the user entered a valid argument? Checking command line arguments

You can put try-except clauses anywhere. Python provides several kinds of exceptions (each of which is of course a class!). Here are some common exception classes: ZeroDivisionError # when you try to divide by zero NameError # when a variable name can't be found MemoryError # when program runs out of memory ValueError # when int() or float() can't parse a string IndexError # when a list or string index is out of range KeyError # when a dictionary key isn't found ImportError # when a module import fails SyntaxError # when the code syntax is uninterpretable

class Date: def __init__(self, day, month, year): try: self.day = int(day) except ValueError: print 'Date constructor: day must be an int value' try: self.month = int(month) except ValueError: print 'Date constructor: month must be an int value' try: self.year = int(year) except ValueError: print 'Date constructor: year must be an int value' Example - enforcing format in the Date class indicates only catches this class of error

import traceback import sys class Date: def __init__(self, day, month, year): try: self.day = int(day) except ValueError: print 'Date constructor: day must be an int value' traceback.print_exc() sys.exit() You may even want to force a program exit with information about the offending line of code: special traceback function that prints information for the exception

Create your own Exception import exceptions class DayFormatException(exceptions.Exception): def __str__(self): print 'Day must be parseable as an int value' DayFormat extends the Python defined Exception class Remember that the __str__() function is what print calls when you try to print an object. What does this mean?

Using your own Exceptions class Date: def __init__(self, day, month, year): try: self.day = int(day) except: raise DayFormatException The DayFormatException will get returned to where ever the constructor was called - there it can be "caught" try: myDate = Date("Ides", "March", "IXIV") except:

Exercise 1 Write a program check_args.py that gets two command line arguments and checks that the first represents a valid int number and that the second one represents a valid float number. Make useful feedback if they are not. > python check_args.py 3 help! help! is not a valid second argument, expected a float value > python check_args.py I_need_somebody I_need_somebody is not a valid first argument, expected an int value

import sys try: arg1 = int(sys.argv[1]) except ValueError: print "'sys.argv[1]' is not a valid first argument, expected an int value" sys.exit() try: arg2 = int(sys.argv[2]) except ValueError: print "'sys.argv[2]' is not a valid second argument, expected a float value" sys.exit()

Exercise 2 Write a class fastaDNA that represents a fasta DNA sequence, with the name and the sequence itself stored as class variables (members). In the constructor, use exception handling to check that the sequence is valid (consists only of the characters 'A', 'C', 'G', 'T', or 'N' (either upper or lower case). Provide useful feedback if not.

import sys import re class fastaDNA: __init__(self, name, sequence): self.name = name match = re.match('[^ACGTNacgtn]') if match != None: print sequence, 'is an invalid DNA sequence' sys.exit() self.sequence = sequence

Challenge Exercise Change your class definition from Exercise 2 so that it useful traceback information so that you can find where in your code you went wrong.