By Ryan Christen Errors and Exceptions.

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

Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
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.
Introduction to Python. What is Python? Interpreted object oriented high level programming language – No compiling or linking neccesary Extensible: add.
Exceptions COMPSCI 105 S Principles of Computer Science.
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.
General Programming Introduction to Computing Science and Programming I.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Functions Chapter 4 Python for Informatics: Exploring Information
Variables, Expressions, and Statements
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Python Conditionals chapter 5
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Exceptions CMSC 201. Overview Exceptions are run-time errors, especially ones that the programmer cannot predict.  example 1: division by zero  example.
 Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes.
CS 177 Week 10 Recitation Slides 1 1 Debugging. Announcements 2 2.
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.
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.
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.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
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”
C++ Exceptions.
Exceptions in Python Error Handling.
Introduction to Computing Science and Programming I
similar concepts, different syntax
George Mason University
Introduction to Python
Lecture 4 Python Basics Part 3.
Why exception handling in C++?
Presented By S.Yamuna AP/IT
Python - Functions.
Variables, Expressions, and Statements
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Java Programming Language
Exception Handling.
Python’s Errors and Exceptions
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Exceptions.
Variables, Expressions, and Statements
Python for Informatics: Exploring Information
Variables, Data Types & Math
Problems Debugging is fine and dandy, but remember we divided problems into compile-time problems and runtime problems? Debugging only copes with the former.
Variables, Expressions, and Statements
Python Syntax Errors and Exceptions
Recursion Taken from notes by Dr. Neil Moore
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Topics Introduction to File Input and Output
Python Exceptions and bug handling
Dealing with Runtime Errors
Control 9 / 25 / 19.
Presentation transcript:

By Ryan Christen Errors and Exceptions

The two types of errors Syntax Errors -These errors are obtained when compiling. -When the error is obtained, the program will point to the line and the part of the code where it got the error. -Python basically does not know the format of the code you put in. Exceptions -These errors happen upon execution of the code. -There are many types, but the type and line will be displayed. -Most of them are not handled by programs

This is an example of a Python syntax error >>> while True print 'Hello world' File "<stdin>", line 1, in ? while True print 'Hello world' ^ SyntaxError: invalid syntax 3 examples of Python exceptions >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: integer division or modulo by zero >>> 4 + spam*3 NameError: name 'spam' is not defined >>> '2' + 2 TypeError: cannot concatenate 'str' and 'int' objects

Handling exceptions with Try When try is executed, it runs the code under it If there happens to be an error, it stops the code and goes to an except of matching type If no except of matching type can be found, then it gives an error like that of prevoius example. The except clauses can hold more then 1 type Only the first except clause will respond to the error. Except clauses can not have any type in them, but this is not recommended. Try can call functions to check.

Example of using try >>> while True: ... try: ... x = int(raw_input("Please enter a number: ")) ... break ... except ValueError: ... print "Oops! That was no valid number. Try again..." ... Example of multiple except uses except (RuntimeError, TypeError, NameError): ... pass

Using else The else clause follows all except clauses If the except clause is not executed, the else clause is. Putting code into an else instead of putting it outside of a try statement can protect it from other exceptions

Example of using else statement for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close()

Exceptions may have variables The exception itself can have variables bound to the exception instance. The variables will be stored in instance.args.

Example of what Exceptions can hold >>> try: ... raise Exception('spam', 'eggs') ... except Exception as inst: ... print type(inst) # the exception instance ... print inst.args # arguments stored in .args ... print inst # __str__ allows args to printed directly ... x, y = inst # __getitem__ allows args to be unpacked directly ... print 'x =', x ... print 'y =', y ... <type 'exceptions.Exception'> ('spam', 'eggs') x = spam y = eggs

Raising Exceptions Using the raise statement, you can give yourself an error! The type of error can be specified. The arguments inside the error can describe the error. (see example). If you do not intend to handle it, put it inside of try code.

Example of using raise >>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: HiThere Using raise and taking care of it >>> try: ... raise NameError('HiThere') ... except NameError: ... print 'An exception flew by!‘ ... Raise ... An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in ? NameError: HiThere

Using finally and with for cleanup Finally is put after everything else after the try statement. It is always runs no matter what, and is good for closing anything open at the end. With is used with files so that they can clean up themselves.

Example showing finally always being printed out >>> def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: ... print "division by zero!" ... else: ... print "result is", result ... finally: ... print "executing finally clause" ... >>> divide(2, 1) result is 2 executing finally clause >>> divide(2, 0) division by zero! >>> divide("2", "1") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'

Example showing proper usage of with, using with a file (yes, it gets its own slide) with open("myfile.txt") as f: for line in f: print line

User-defined Exceptions It is possible to create your own exceptions. Usually in some form they should be derived from the Exception class. Usually also create a base class, and subclass for certain examples Useful for getting information you want about an error.