Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dealing with Runtime Errors

Similar presentations


Presentation on theme: "Dealing with Runtime Errors"— Presentation transcript:

1 Dealing with Runtime Errors
Exception Handling Dealing with Runtime Errors

2 Exception An exception is an error that occurs at runtime
Types of exceptions: NameError Caused by: Misspelled variable or function name Use of variable in expression before it is assigned an initial value TypeError Operand of incorrect type for operator ValueError Passing wrong type of data to function

3 Exception Handling You can write an exception handler to intercept an exception and prevent your program from crashing. Use a try - except statement to intercept exceptions: try: # guarded statements except Exception as e: # deal with the exception

4 Exception Handling Example
How try-except works: Guarded statements execute one at a time If an exception occurs while executing a statement, the rest of the guarded statements are skipped, and the exception handler executes After a try-except statement executes, the program continues normally try: ageStr = input('Enter your age:') age = int(ageStr) print('You are', age, 'years old.') except Exception as e: print('Something went wrong: ', e)

5 Exception Parameter You can optionally define an exception parameter with “as”: except Exception as e The exception parameter contains information about the exception Print out the exception parameter so that the user knows what went wrong try: ageStr = input('Enter your age:') age = int(ageStr) print('You are', age, 'years old.') except Exception as e: print('Something went wrong: ', e)

6 Exception-Specific Handling
Different kinds of exceptions occur ValueError - attempt to convert non- numeric data to int or float ZeroDivisionError - division by zero A try-except statement can perform exception-specific handling by defining more than one exception handler Put the general Exception as e case at the end Exception handlers are tried in order The first handler that matches the exception will handle it try: total = float(input('Enter total amount:')) count = float(input('Enter count:')) avg = total / count print('average =', avg) except ValueError: print('Invalid input') except ZeroDivisionError: print('Can't divide by zero') except Exception as e: print('Something went wrong: ', e)

7 Exception Propagation
An exception that occurs inside a function propagates to its caller if not handled A single exception handler can catch exceptions that occur anywhere in the program However, all it can do is a graceful shutdown Pro tip: Avoid defining a “master” exception handler like this during program development Complicates debugging def square(n): return int(n) * int(n) def main(): num = input('Enter a number:') print(num, 'squared is:', square(num)) try: main() except Exception as e: print('Something went wrong: ', e)

8 Exception Handling in Web Apps
Need to display a clean error message to user Return an HTML page with a user-friendly error message Need to log a detailed error message to console Use traceback module: import traceback traceback.print_exc() Example: examples/webapps/webguess.py


Download ppt "Dealing with Runtime Errors"

Similar presentations


Ads by Google