120 likes | 271 Views
Exception Handling. CSIS 1595: Fundamentals of Programming and P roblem Solving 1. What is an Exception?. Error : Fault in program that causes it to incorrectly implement a concept Example: math.sqrt function that given incorrect result Exception :
E N D
Exception Handling CSIS 1595: Fundamentals of Programming and Problem Solving 1
What is an Exception? • Error: Fault in program that causes it to incorrectly implement a concept • Example: math.sqrt function that given incorrect result • Exception: Situation where concept itself undefined • Example: math.sqrt(-1) • Often caused by user error
Handling Exceptions • Key question: What should Python do if exception occurs? • Ignore problem (array out of bounds in C) • Shut down program • Print message… • What is best option? • Bank software Save data, shut down, report error • Autopilot software Display alert, but keep running!
Handling Exceptions • Optimal solution: • Python should “notify” program about problem • Program should be given option of handling problem in whatever way is best for that circumstance Your code Python environment Code that causes exceptionx = int(“fred”) Code to handleexception call Internal code for intfunction detectsproblem and signalsexception to user signal
Exception Handling Syntax try: code that might cause exception other code that should not be run if exception occurs except exception type: code to run if exception occurs …
Exception Handling Branching try: code that might cause exception other code in try block … other code in try block except exception type: code to run if exception rest of code exception occurs then go to rest of code
Exception Handling Branching try: code that might cause exception other code in try block … other code in try block except exception type: code to run if exception rest of code no exception occurs, so skip the exception block
Some Python Exceptions • Key idea: Exception handling only way to detect and handle some types of errors • Parsing non-numeric values • Opening nonexistent files
Simple Example • Program inputs and squares number • Possible exception: User enters non-numeric value • Would cause ValueError
Complex Example • Program reads numbers from file, prints total • Reading from file IOError • Parsing numbers to add to total ValueError • Key question: How to handle each? • Can’t open file Quit program • Number can’t be parsed Skip it and keep running (and print warning)