Py Lec S 21 5 - ExceptionBasic PDF

Title Py Lec S 21 5 - ExceptionBasic
Author Amuel Wilson
Course Database Management and Interfacing
Institution Algonquin College
Pages 16
File Size 866.3 KB
File Type PDF
Total Downloads 107
Total Views 205

Summary

ExceptionBasic...


Description

Error Handling

Error types 





Syntax error:  When: caught by Python interpreter  How: Python sends SyntaxError message to STDERR Runtime error:  When: an “unexecutable” condition occurs  Note: Often caused by invalid input from file, user, etc.  How: Python “raises an exception” Logic error:  When: discovered during program testing  Note: Can be caused by incorrect variable name, indentation, operator precedence, loop (off-by-one)  How: mitigated by using PDL/test plan



Purpose of error handling Purpose of error handling: prevent program from stopping due to unexpected condition at runtime.  Instead:  either terminate gracefully  or handle error appropriately & continue  Two complimentary approaches:  Defensive programming:  Code for anticipated errors  Example: zero division error  Exception handling:  Handle exceptional conditions raised by Python during program execution  Example: Missing file, DB connectivity  Note: What falls under “anticipated” and “exceptional” can be debatable. 



Error handling example 

Defensive coding a = int(input(“Num1: ”)) b = int(input(“Num2: “)) if b != 0: print(a/b) else: print(“Error: Division by zero!”)



Unhandled exception 

Unexecutable condition not handled a = int(input(“Num1: ”)) b = int(input(“Num2: “)) # user input: 0 print(a/b)



Named exception is raised; program aborts Traceback (most recent call last): File "./calc.py", line 5, in print(a/b) ZeroDivisionError: division by zero



Handling exceptional errors  

“Try” to execute code, and if an “exception” during runtime occurs, “handle” it. Benefits:  Program code & error handling code are distinct: can improve code readability & maintenance.  Error handling code can be written anywhere in the process hierarchy: separation of error handling responsibilities.  “Exceptions” are named Python objects that include relevant information regarding the unexecutable condition.



Exception handling process Raising an exception: Python “raises an exception” when encountering a runtime error. 2. Handling an exception: Python expects an exception to be “handled” by program.  If handled, Python continues program execution.  If not handled, Python terminates program with error message to STDERR.  Python provides clauses for exception handling:  try/except: required clauses for error handling  else, finally: optional clauses for error handling  raise: optional clause to explicitly raise exceptions 1.

 Example:

Program flow with try & except



Code try: # attempt execution of statements x=2/0 # exception raised except: # if exception raised execute statements print(“Exception raised!”)



Output Exception raised!



Program flow 





The try clause is used to raise exceptions  All statements in the try clause are executed.  If no exception occurs, the statements in the except clause are not executed. The except clause is used to handle raised exceptions  When an exception occurs in the try clause the rest of the statements in the try clause are not executed.  Instead, all statements in the except clause are executed. Program execution  Program execution continues after the try & except block.

 Example:

Program flow with try & except



Code try: # attempt execution of statements print(“Hello …”) # executed x=2/0 # exception raised print(“… world”) # not executed except: # if exception raised execute statements print(“Exception raised!”) print(“~ Done with experiment ~”)



Output Hello … Exception raised! ~ Done with experiment ~



Example: Exception handling 



Using unnamed exception try: return 2/0 except: # unnamed exception print(“Error”) Using named exception try: return 2/0 except ZeroDivisionError: # named exception print(“Error: zero division”)



Error handling options   

Continue program if error recoverable. Terminate program gracefully if error unrecoverable. Pass on error handling to higher-level function.  Error state usually communicated to higher-level function with return value.  Return value must be tested in calling function.  Return value can be ignored, potentially further compounding error condition.



Exception handling actions 





Handle quietly at the point of the raised exception (and keep running).  Note: The pass statement does “nothing” but is considered valid for exception handling. Make the exception visible by:  displaying an error message  logging  re-raising an exception for calling process Manage the exception in a program specific way.  Example: Use default values if appropriate values have not been provided.



Exception handling actions – example 

Inform & handle try: x=2/0 except ZeroDivisionError: print(“Cannot divide by zero!”) x=0 print(“Result:”, x)

Unhandled exception & traceback 





When an exception is not handled in the current process, the process stops and passes the exception to the calling process, which passes it to the calling process until:  Either the exception is handled  Or program execution stops Python displays a “Traceback”, which follows the exception from the point of occurrence up the invocation chain. Example:  Main program calls function F  Function F raises exception  If exception is not handled in F, it is passed to main  If exception is not handled in main, program stops: the error displays the path the exception traveled.



Code def divide() 2/0 def calc() divide() calc() # main -> calc -> divide: exception



Traceback error message Traceback (most recent call last): File “./main.py", line 9, in calc() File “./main.py", line 7, in calc divide() File “./main.py", line 5, in divide 2/0 ZeroDivisionError: division by zero...


Similar Free PDFs