Understand Python Exceptions Handling and Error Management

compsci 105 ss 2015 principles of computer science n.w
1 / 25
Embed
Share

Dive into the world of Python exceptions handling, learning how to gracefully deal with errors in your code to enhance readability, reliability, and maintainability. Explore examples, best practices, and essential techniques for effective error management in Python programming.

  • Python
  • Exceptions Handling
  • Error Management
  • Programming Techniques

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. COMPSCI 105 SS 2015 Principles of Computer Science Exceptions

  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? 2 COMPSCI 105 Lecture05-06

  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 3 COMPSCI 105 Lecture05-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. 4 COMPSCI 105 Lecture05-06

  5. Example01.py 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 def divide(a, b): result = a / b return result x = divide(5, 0) print(x) where Traceback (most recent call last): File ...", line 5, in <module> x = divide(5, 0) File ...", line 2, in divide result = a / b ZeroDivisionError: division by zero reason 5 COMPSCI 105 Lecture05-06

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

  7. Handling input error Check for valid input first What if a is not a number? 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) 7 COMPSCI 105 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. 8 COMPSCI 105 Lecture05-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 try: statement block except: statement block exception handling statements exception handling statements Advantages of catching exceptions: It allows you to fix the error It prevents the program from automatically terminating 9 COMPSCI 105 Lecture05-06

  10. 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 Example02.py Example 1 Case 1: No error divide(5,5) x = divide(5, 5) print ("Program can continue to run...") print(x) try-block Program can continue to run... 1.0 Case 2: Invalid input divide(5,0), divide(5, Hello ) x = divide(5, 'hello') print ("Program can continue to run...") print (x) Error Program can continue to run... Error in input data 10 COMPSCI 105 Lecture05-06

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

  13. Example03.py Specifying the exceptions Case 1: No error 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) 1.0 Case 2: is not a number Case 3: Divided by zero x = divide('abc', 5) print(x) Type of operands is incorrect x = divide(5, 0) print(x) Divided by zero 13 COMPSCI 105 Lecture05-06

  14. Example04.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. 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) Traceback (most recent call last): File ...", line 11, in <module> x = divide('abc', 0)File ...", line 3, in divide result = a / b TypeError: unsupported operand type(s) for /: 'str' and 'int' 14 COMPSCI 105 Lecture05-06

  15. Example05.py Order of except clauses Specific exception block must come before any of their general exception block 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 15 COMPSCI 105 Lecture05-06

  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 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 16 COMPSCI 105 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 try: except: statement block here more statements here (undo operations) finally: more statements here (close operations) 17 COMPSCI 105 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. try: except: statement block here more statements here (undo operations) else: more statements here (close operations) 18 COMPSCI 105 Lecture05-06

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

  20. Exercise 2 What is the output of the following program when x is 1, 0 and '0'? 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') 20 COMPSCI 105 Lecture05-06

  21. Raising an exception: You can create an exception by using the raise statement raise Error('Error message goes here') 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: def checkLevel(level): if level < 1: raise ValueError('Invalid level!') else: print (level) Traceback (most recent call last): ... raise ValueError('Invalid level!') ValueError: Invalid level! 21 COMPSCI 105 Lecture05-06

  22. Example07.py Handling Exceptions Put code that might create a runtime error is enclosed in a try block 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)) Problem: Invalid level! def checkLevel(level): try: if level < 1: raise ValueError('Invalid level!') ... except ValueError as x: pass 22 COMPSCI 105 Lecture05-06

  23. Using Exceptions 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. Lecture05-06 COMPSCI 105 23

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

Related


More Related Content