Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
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.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
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.
An Introduction to Python and Its Use in Bioinformatics
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
Exceptions COMPSCI 105 S Principles of Computer Science.
Python Crash Course Programming Bachelors V1.0 dd Hour 5.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 19 Handling Exceptions 6/09/09 Python Mini-Course: Lesson 19 1.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
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.
Functions Reading/writing files Catching exceptions
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?
Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors.
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 –
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Exceptions CMSC 201. Overview Exceptions are run-time errors, especially ones that the programmer cannot predict.  example 1: division by zero  example.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
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.
Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
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.
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
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:
Python Exceptions and bug handling Peter Wad Sackett.
Exception Handling How to handle the runtime errors.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
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
Exceptions and File Input
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
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.
By Ryan Christen Errors and Exceptions.
Topics Introduction to File Input and Output
Python Exceptions and bug handling
UW CSE 190p Section 7/19, Summer 2012 Dun-Yu Hsiao.
Dealing with Runtime Errors
Presentation transcript:

Lecture 07 – Exceptions

 Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime errors gracefully  'catching' an exception of the appropriate type  Generate exceptions when appropriate  raise an exception 2COMPSCI Computer Science Fundamentals

 Typical code with no errors 3COMPSCI Computer Science Fundamentals def divide(a, b): result = a / b return result x = divide(5, 5) print(x)

 What if the function is passed a value that causes a divide by zero?  Error caused at runtime  Error occurs within the function  Problem is with the input  What can we do? 4COMPSCI Computer Science Fundamentals def divide(a, b): result = a / b return result x = divide(5, 0) print(x)

 Check for valid input first  Only accept input where the divisor is non-zero 5COMPSCI Computer Science Fundamentals def divide(a, b): if b == 0: result = 'Error: cannot divide by zero' else: result = a / b return result x = divide(5, 0) print(x)

 Check for valid input first  What if b is not a number? 6COMPSCI Computer Science Fundamentals def divide(a, b): if (type(b) is not int and type(b) is not float): result = "Error: divisor is not a number" elif b == 0: result = 'Error: cannot divide by zero' else: result = a / b return result x = divide(5, 'hello') print(x)

 Check for valid input first  What if a is not a number? 7COMPSCI Computer Science Fundamentals def divide(a, b): if (type(b) is not int and type(b) is not float or type(a) is not int and type (a) is not float): result = ('Error: one or more operands' + ' is not a number') elif b != 0: result = a / b else: result = 'Error: cannot divide by zero' return result x = divide(5, 'hello') print(x)

 Code that might create a runtime error is enclosed in a try block  Statements are executed sequentially as normal  If an error occurs then the remainder of the code is skipped  The code starts executing again at the except clause  The exception is "caught" 8COMPSCI Computer Science Fundamentals try: statement block except: exception handling statements

 Assume input is correct  Deal with invalid input an an exceptional case 9COMPSCI Computer Science Fundamentals def divide(a, b): try: result = a / b except: result = 'Error in input data' return result x = divide(5, 'hello') print(x)

 What is the output of the following? 10COMPSCI Computer Science Fundamentals def divide(dividend, divisor): try: quotient = dividend / divsor except: quotient = 'Error in input data' return quotient x = divide(5, 0) print(x) x = divide('hello', 'world') print(x) x = divide(5, 5) print(x)

 The general except clause catching all runtime errors  Sometimes that can hide problems 11COMPSCI Computer Science Fundamentals def divide(dividend, divisor): try: quotient = dividend / divsor except: quotient = 'Error in input data' return quotient x = divide(5, 2.5) print(x)

 Can choose to catch only some exceptions 12COMPSCI Computer Science Fundamentals def divide(a, b): try: result = a / b except TypeError: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result x = divide('hello', 0) print(x)

 Any kind of built-in error can be caught  Check the Python documentation for the complete list 13COMPSCI Computer Science Fundamentals BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError

 raise  Creates a runtime error – by default, the most recent runtime error  raise Error('Error message goes here') 14COMPSCI Computer Science Fundamentals try: statement block here except: more statements here (undo operations) raise raise ValueError("My very own runtime error")

 Given the following function that converts a day number into the name of a day of the week, write code that will generate an informative exception if the name is outside the desired range. 15COMPSCI Computer Science Fundamentals def weekday(n): names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] return names[n]

 Given the following function that converts a day number into the name of a day of the week, write code that will generate an informative exception if the name is outside the desired range. 16COMPSCI Computer Science Fundamentals def weekday(n): if n not in range(0, 8): raise ValueError('Data must be between 0 and 7 inclusive') names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] return names[n]

 Modify the following function that calculates the mean value of a list of numbers to ensure that the function generates an informative exception when input is unexpected 17COMPSCI Computer Science Fundamentals def mean(data): sum = 0 for element in data: sum += element mean = sum / len(data) return mean

 finally  Executed after the try and except blocks, but before the entire try-except ends  Often used with files to close the file  else  Executed only if the try clause completes with no errors 18COMPSCI Computer Science Fundamentals try: statement block here except: more statements here (undo operations) finally: more statements here (close operations) try: statement block here except: more statements here (undo operations) else: more statements here (close operations)

19COMPSCI Computer Science Fundamentals try: file = open('test.txt') file.write('Trying to write to a read-only file') except IOError: print('Error: cant find file or read data') else: print("Written content in the file successfully") finally: file.close()

 What is the output of the following program when x is 1, 0 and '0'? 20COMPSCI Computer Science Fundamentals try: print('Trying some code') 2 / x except ZeroDivisionError: print('ZeroDivisionError raised here') except: print('Error raised here') raise else: print('Else clause') finally: print('Finally')

 Exceptions alter the flow of control  When an exception is raised, execution stops  When the exception is caught, execution starts again  try… except blocks are used to handle problem code  Can ensure that code fails gracefully  Can ensure input is acceptable  raise  Creates a runtime exception  finally  Executes code after the exception handling code 21COMPSCI Computer Science Fundamentals