Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.

Similar presentations


Presentation on theme: "Exceptions COMPSCI 105 SS 2015 Principles of Computer Science."— Presentation transcript:

1 Exceptions COMPSCI 105 SS 2015 Principles of Computer Science

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 Example 1  Case 1: No error  divide(5,5)  Case 2: Invalid input  divide(5,0), divide(5, ‘Hello’) COMPSCI 10510 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... 1.0 try-block Program can continue to run... 1.0

11 Exercise 01  What is the output of the following? COMPSCI 10511 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

12 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

13 Specifying the exceptions  Case 1:  No error  Case 2:  is not a number COMPSCI 10513 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

14 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 10514 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

15 Order of except clauses  Specific exception block must come before any of their general exception block COMPSCI 10515 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

16 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 10516 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

17 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 10517 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

18 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 10518 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

19 Example  Case 1:  No error  Case 2:  Divided by zero COMPSCI 10519 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

20 Exercise 2  What is the output of the following program when x is 1, 0 and '0'? COMPSCI 10520 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

21 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 10521 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!

22 Handling Exceptions  Put code that might create a runtime error is enclosed in a try block COMPSCI 10522 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

23  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

24 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 10524 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

25 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


Download ppt "Exceptions COMPSCI 105 SS 2015 Principles of Computer Science."

Similar presentations


Ads by Google