Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.

Slides:



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

Topics Introduction Types of Errors Exceptions Exception Handling
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.
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.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
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.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
Exceptions COMPSCI 105 S Principles of Computer Science.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 19 Handling Exceptions 6/09/09 Python Mini-Course: Lesson 19 1.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Chapter 12: Exception Handling
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.
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?
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 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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
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.
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.
Python Exceptions and bug handling Peter Wad Sackett.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
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. 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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
COMPSCI 107 Computer Science Fundamentals
Exceptions in Python Error Handling.
George Mason University
Part IX Fundamentals of C and C++ Programming Exception Handling
Exceptions and files Taken from notes by Dr. Neil Moore
Chapter 14: Exception Handling
Topics Introduction to File Input and Output
Python’s Errors and Exceptions
Exceptions and files Taken from notes by Dr. Neil Moore
Part B – Structured Exception Handling
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
Exception Handling.
Python Exceptions and bug handling
UW CSE 190p Section 7/19, Summer 2012 Dun-Yu Hsiao.
Dealing with Runtime Errors
Presentation transcript:

Exceptions COMPSCI 105 SS 2015 Principles of Computer Science

Exercise  Week 2:  Work on Lab1 (Mon/Tue, basic Python Syntax) and Lab2 (Thurs/Fri, classes)  Lab1 will be closed at 23:59 Wednesday, 14 Jan  Lab2 will be closed at 23:59 Saturday, 17 Jan  PreLab02: Exceptions, Json and Complexity  Prelab02 will be closed at 23:59 Monday, 19 Jan  Exercise  Implement the __lt__ method  Note: How to compare two fractions? Lecture05-06COMPSCI 1052

Learning outcomes  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 COMPSCI 1053Lecture05-06

Introduction  Errors occur in software programs. However, if you handle errors properly, you'll greatly improve your program’s readability, reliability and maintainability.  Python uses exceptions for error handling  Exception examples:  Attempt to divide by ZERO  Couldn’t find the specific file to read  The run-time system will attempt to handle the exception (default exception handler), usually by displaying an error message and terminating the program. COMPSCI 1054Lecture05-06

Handling unexpected input values  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?  You can try to check for valid input first COMPSCI 1055 def divide(a, b): result = a / b return result x = divide(5, 0) print(x) def divide(a, b): result = a / b return result x = divide(5, 0) print(x) Traceback (most recent call last): File “...", line 5, in x = divide(5, 0) File “...", line 2, in divide result = a / b ZeroDivisionError: division by zero Traceback (most recent call last): File “...", line 5, in x = divide(5, 0) File “...", line 2, in divide result = a / b ZeroDivisionError: division by zero where reason Lecture05-06 Example01.py

Divide by zero error  Check for valid input first  Only accept input where the divisor is non-zero  What if “b” is not a number? COMPSCI 1056 def divide(a, b): if b == 0: result = 'Error: cannot divide by zero' else: result = a / b return result def divide(a, b): if b == 0: result = 'Error: cannot divide by zero' else: result = a / b return result 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'... 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'... Lecture05-06

Handling input error  Check for valid input first  What if “a” is not a number? COMPSCI 1057 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 = 'Error: cannot divide by zero' else: result = a / b return result x = divide(5, 'hello') print(x) 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 = 'Error: cannot divide by zero' else: result = a / b return result x = divide(5, 'hello') print(x) Lecture05-06

What is an Exception?  An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program.  When an error occurs within a method, the method creates an exception object and hands it off to the runtime system.  The exception object contains  information about the error, including its type and the state of the program when the error occurred.  Creating an exception object and handing it to the runtime system is called throwing an exception. COMPSCI 1058Lecture05-06

Handling exceptions  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“  Advantages of catching exceptions:  It allows you to fix the error  It prevents the program from automatically terminating COMPSCI 1059 try: statement block except: exception handling statements try: statement block except: exception handling statements Lecture05-06

Example 1  Case 1: No error  divide(5,5)  Case 2: Invalid input  divide(5,0), divide(5, ‘Hello’) COMPSCI def divide(a, b): try: result = a / b print ("This will be not be printed") except: result = 'Error in input data' print ("Error") return result def divide(a, b): try: result = a / b print ("This will be not be printed") except: result = 'Error in input data' print ("Error") return result Lecture05-06 Example02.py x = divide(5, 'hello') print ("Program can continue to run...") print (x) x = divide(5, 'hello') print ("Program can continue to run...") print (x) Error Program can continue to run... Error in input data Error Program can continue to run... Error in input data x = divide(5, 5) print ("Program can continue to run...") print(x) x = divide(5, 5) print ("Program can continue to run...") print(x) try-block Program can continue to run try-block Program can continue to run

Exercise 01  What is the output of the following? COMPSCI 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) 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) Lecture05-06

Danger in catching all exceptions  The general except clause catching all runtime errors  Sometimes that can hide problems  You can put two or more except clauses, each except block is an exception handler and handles the type of exception indicated by its argument in a program.  The runtime system invokes the exception handler when the handler is the FIRST ONE matches the type of the exception thrown.  It executes the statement inside the matched except block, the other except blocks are bypassed and continues after the try-except block. COMPSCI 10512Lecture05-06

Specifying the exceptions  Case 1:  No error  Case 2:  is not a number COMPSCI def divide(a, b): try: result = a / b except TypeError: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result 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(5, 5) print(x) x = divide(5, 5) print(x) 1.0 x = divide('abc', 5) print(x) x = divide('abc', 5) print(x) Type of operands is incorrect  Case 3:  Divided by zero x = divide(5, 0) print(x) x = divide(5, 0) print(x) Divided by zero Lecture05-06 Example03.py

Exception not Matched  If no matching except block is found, the run-time system will attempt to handle the exception, by terminating the program. COMPSCI def divide(a, b): try: result = a / b except IndexError: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result def divide(a, b): try: result = a / b except IndexError: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result x = divide(5, 5) print(x) x = divide(5, 5) print(x) Traceback (most recent call last): File “...", line 11, in x = divide('abc', 0)File “...", line 3, in divide result = a / b TypeError: unsupported operand type(s) for /: 'str' and 'int' Traceback (most recent call last): File “...", line 11, in x = divide('abc', 0)File “...", line 3, in divide result = a / b TypeError: unsupported operand type(s) for /: 'str' and 'int' Lecture05-06 Example04.py

Order of except clauses  Specific exception block must come before any of their general exception block COMPSCI def divide(a, b): try: result = a / b except: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result def divide(a, b): try: result = a / b except: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result result = a / b SyntaxError: default 'except:' must be last result = a / b SyntaxError: default 'except:' must be last Lecture05-06 Example05.py

Exceptions  Any kind of built-in error can be caught  Check the Python documentation for the complete list  Some popular errors:  ArithmeticError: various arithmetic errors  ZeroDivisionError  IndexError: a sequence subscript is out of range  TypeError: inappropriate type  ValueError:  has the right type but an inappropriate value  IOError: Raised when an I/O operation  EOFError:  hits an end-of-file condition (EOF) without reading any data  … COMPSCI 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 Lecture05-06

The Finally clause  The finally block is optional, and is not frequently used  Executed after the try and except blocks, but before the entire try- except ends  Code within a finally block is guaranteed to be executed if any part of the associated try block is executed regardless of an exception being thrown or not  It allows for cleanup of actions that occurred in the try block but may remain undone if an exception is caught  Often used with files to close the file COMPSCI 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) finally: more statements here (close operations) Lecture05-06

The else clause  Executed only if the try clause completes with no errors  It is useful for code that must be executed if the try clause does not raise an exception. COMPSCI try: statement block here except: more statements here (undo operations) else: more statements here (close operations) try: statement block here except: more statements here (undo operations) else: more statements here (close operations) Lecture05-06

Example  Case 1:  No error  Case 2:  Divided by zero COMPSCI def divide(a, b): try: result = a / b except ZeroDivisionError: result = 'Divided by zero' else: print("result is", result) finally: print("executing finally clause") def divide(a, b): try: result = a / b except ZeroDivisionError: result = 'Divided by zero' else: print("result is", result) finally: print("executing finally clause") Lecture05-06 x = divide(2, 1) result is 2.0 executing finally clause result is 2.0 executing finally clause x = divide(2, 0) executing finally clause  Case 3:  Error x = divide('2', '1') executing finally clause Traceback (most... TypeError: unsupported operand type(s)... executing finally clause Traceback (most... TypeError: unsupported operand type(s)... Example06.py

Exercise 2  What is the output of the following program when x is 1, 0 and '0'? COMPSCI def testing(x): try: print('Trying some code') 2 / x except ZeroDivisionError: print('ZeroDivisionError raised here') except: print('Error raised here') else: print('Else clause') finally: print('Finally') def testing(x): try: print('Trying some code') 2 / x except ZeroDivisionError: print('ZeroDivisionError raised here') except: print('Error raised here') else: print('Else clause') finally: print('Finally') Lecture05-06

Raising an exception:  You can create an exception by using the raise statement  The program stops immediately after the raise statement; and any subsequent statements are not executed.  It is normally used in testing and debugging purpose  Example: COMPSCI def checkLevel(level): if level < 1: raise ValueError('Invalid level!') else: print (level) def checkLevel(level): if level < 1: raise ValueError('Invalid level!') else: print (level) raise Error('Error message goes here') Lecture05-06 Traceback (most recent call last):... raise ValueError('Invalid level!') ValueError: Invalid level! Traceback (most recent call last):... raise ValueError('Invalid level!') ValueError: Invalid level!

Handling Exceptions  Put code that might create a runtime error is enclosed in a try block COMPSCI def checkLevel(level): try: if level < 1: raise ValueError('Invalid level!') else: print (level) print ('This print statement will not be reached.') except ValueError as x: print ('Problem: {0}'.format(x)) def checkLevel(level): try: if level < 1: raise ValueError('Invalid level!') else: print (level) print ('This print statement will not be reached.') except ValueError as x: print ('Problem: {0}'.format(x)) Lecture05-06 Problem: Invalid level! def checkLevel(level): try: if level < 1: raise ValueError('Invalid level!')... except ValueError as x: pass def checkLevel(level): try: if level < 1: raise ValueError('Invalid level!')... except ValueError as x: pass Example07.py

 When to use try catch blocks?  If you are executing statements that you know are unsafe and you want the code to continue running anyway.  When to raise an exception?  When there is a problem that you can't deal with at that point in the code, and you want to "pass the buck" so the problem can be dealt with elsewhere. Using Exceptions 23COMPSCI 105 Lecture05-06

Exercise 3  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 COMPSCI def mean(data): sum = 0 for element in data: sum += element mean = sum / len(data) return mean def mean(data): sum = 0 for element in data: sum += element mean = sum / len(data) return mean Lecture05-06

Summary  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  finally  Executes code after the exception handling code COMPSCI 10525Lecture05-06