Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.

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

Perkovic, Chapter 7 Functions revisited Python Namespaces
CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Introduction to Computing Using Python Namespaces and Exceptions, revisited  Encapsulation in Functions  Global versus Local Namespaces  Exceptional.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Introduction to Computing Using Python Text Data, File I/O, and Exceptions  Strings, revisited  Formatted output  File Input/Output  Errors and Exceptions.
Introduction to Computing Using Python Text Data, File I/O, and Exceptions  Strings, revisited  Formatted output  File Input/Output  Errors and Exceptions.
Introduction to Computing Using Python Imperative Programming  Python Programs  Interactive Input/Output  One-Way and Two-Way if Statements  for Loops.
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.
 2002 Prentice Hall. All rights reserved. 1 Chapter 2 – Introduction to Python Programming Outline 2.1 Introduction 2.2 First Program in Python: Printing.
Exceptions COMPSCI 105 S Principles of Computer Science.
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
Introduction to Computing Using Python Python  Python is an interactive language.  Java or C++: compile, run  Also, a main function or method  Python:
Python Mini-Course University of Oklahoma Department of Psychology Lesson 19 Handling Exceptions 6/09/09 Python Mini-Course: Lesson 19 1.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
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.
Python – Part 3 Functions 1. Function Calls Function – A named sequence of statements that performs a computation – Name – Sequence of statements “call”
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?
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors.
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Functions Chapter 4 Python for Informatics: Exploring Information
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
1. Understand how to catch errors in a program 2. Know how to filter user input to stop incorrect data.
Python Conditionals chapter 5
Python – Part 3 Functions 1. Getting help Start the Python interpreter and type help() to start the online help utility. Or you can type help(print) to.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Exceptions CMSC 201. Overview Exceptions are run-time errors, especially ones that the programmer cannot predict.  example 1: division by zero  example.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
CS 177 Week 10 Recitation Slides 1 1 Debugging. Announcements 2 2.
Variables, Types, Expressions Intro2CS – week 1b 1.
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.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Exception Handling How to handle the runtime errors.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Control Statements 1. Conditionals 2 Loops 3 4 Simple Loop Examples def echo(): while echo1(): pass def echo1(): line = input('Say something: ') print('You.
Xi Wang Yang Zhang. 1. Strings 2. Text Files 3. Exceptions 4. Classes  Refer to basics 2.py for the example codes for this section.
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”
COMPSCI 107 Computer Science Fundamentals
Exceptions in Python Error Handling.
George Mason University
Introduction to Python
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Chapter 3 Instructor: Zhuojun Duan
Exceptions and File Input
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Exception Handling.
Python’s Errors and Exceptions
Exceptions and files Taken from notes by Dr. Neil Moore
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Python Syntax Errors and Exceptions
By Ryan Christen Errors and Exceptions.
Exception Handling COSC 1323.
Topics Introduction to File Input and Output
Python Exceptions and bug handling
Dealing with Runtime Errors
Presentation transcript:

Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors

Introduction to Computing Using Python Types of errors >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str’ >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt’ >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str’ >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt’ We saw different types of errors in this chapter There are basically two types of errors: syntax errors erroneous state errors

Introduction to Computing Using Python Syntax errors >>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax >>> lst = [4;5;6] SyntaxError: invalid syntax >>> for i in range(10): print(i) SyntaxError: expected an indented block >>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax >>> lst = [4;5;6] SyntaxError: invalid syntax >>> for i in range(10): print(i) SyntaxError: expected an indented block Syntax errors are errors that are due to the incorrect format of a Python statement They occur while the statement is being translated to machine language and before it is being executed.

Introduction to Computing Using Python Erroneous state errors >>> 3/0 Traceback (most recent call last): File " ", line 1, in ZeroDivisionError: division by zero >>> 3/0 Traceback (most recent call last): File " ", line 1, in ZeroDivisionError: division by zero >>> lst Traceback (most recent call last): File " ", line 1, in NameError: name 'lst' is not defined >>> lst Traceback (most recent call last): File " ", line 1, in NameError: name 'lst' is not defined >>> lst = [12, 13, 14] >>> lst[3] Traceback (most recent call last): File " ", line 1, in IndexError: list index out of range >>> lst = [12, 13, 14] >>> lst[3] Traceback (most recent call last): File " ", line 1, in IndexError: list index out of range >>> lst * lst Traceback (most recent call last): File " ", line 1, in lst * lst TypeError: can't multiply sequence by non-int of type 'list’ >>> lst * lst Traceback (most recent call last): File " ", line 1, in lst * lst TypeError: can't multiply sequence by non-int of type 'list’ The “error” object is called an exception; the creation of an exception due to an error is called the raising of an exception This object has a type that is related to the type of error The object contains information about the error The default behavior is to print this information and interrupt the execution of the statement. >>> int('4.5') Traceback (most recent call last): File " ", line 1, in ValueError: invalid literal for int() with base 10: '4.5' >>> int('4.5') Traceback (most recent call last): File " ", line 1, in ValueError: invalid literal for int() with base 10: '4.5' When an error occurs, an “error” object is created

Introduction to Computing Using Python Exception types Some of the built-in exception classes: ExceptionExplanation KeyboardInterrupt Raised when user hits Ctrl-C, the interrupt key OverflowError Raised when a floating-point expression evaluates to a value that is too large ZeroDivisionError Raised when attempting to divide by 0 IOError Raised when an I/O operation fails for an I/O-related reason IndexError Raised when a sequence index is outside the range of valid indexes NameError Raised when attempting to evaluate an unassigned identifier (name) TypeError Raised when an operation of function is applied to an object of the wrong type ValueError Raised when operation or function has an argument of the right type but incorrect value

Introduction to Computing Using Python Catching and handling exceptions It is possible to override the default behavior (print error information and “crash”) when an exception is raised, using try / except statements try: strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) except: print('Enter your age using digits 0-9!') try: strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) except: print('Enter your age using digits 0-9!') >>> =============== RESTART ============== >>> Enter your age: fifteen Traceback (most recent call last): File "/Users/me/age1.py", line 2, in intAge = int(strAge) ValueError: invalid literal for int() with base 10: 'fifteen' >>> >>> =============== RESTART ============== >>> Enter your age: fifteen Traceback (most recent call last): File "/Users/me/age1.py", line 2, in intAge = int(strAge) ValueError: invalid literal for int() with base 10: 'fifteen' >>> >>> ========== RESTART ========== >>> Enter your age: fifteen Enter your age using digits 0-9! >>> >>> ========== RESTART ========== >>> Enter your age: fifteen Enter your age using digits 0-9! >>> Default behavior: If an exception is raised while executing the try block, then the block of the associated except statement is executed The except code block is the exception handler

Introduction to Computing Using Python Format of a try / except statement pair try: except: try: except: The format of a try / except pair of statements is: The exception handler handles any exception raised in the try block The except statement is said to catch the (raised) exception It is possible to restrict the except statement to catch exceptions of a specific type only try: except : try: except :

>>> readAge('age.txt') Value cannot be converted to integer. >>> >>> readAge('age.txt') Value cannot be converted to integer. >>> Introduction to Computing Using Python Format of a try / except statement pair It is possible to restrict the except statement to catch exceptions of a specific type only def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is', age) except ValueError: print('Value cannot be converted to integer.') def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is', age) except ValueError: print('Value cannot be converted to integer.') 1 fifteen age.txt >>> readAge('age.txt') Value cannot be converted to integer. >>> readAge('age.text') Traceback (most recent call last): File " ", line 1, in readAge('age.text') File "/Users/me/ch7.py", line 12, in readAge infile = open(filename) IOError: [Errno 2] No such file or directory: 'age.text' >>> >>> readAge('age.txt') Value cannot be converted to integer. >>> readAge('age.text') Traceback (most recent call last): File " ", line 1, in readAge('age.text') File "/Users/me/ch7.py", line 12, in readAge infile = open(filename) IOError: [Errno 2] No such file or directory: 'age.text' >>> default exception handler prints this