90 likes | 116 Views
Exceptions in Python. Error Handling. Error handling. What happens when a Python rogram is running and an error occurs? Python IDEs will “catch” the error signal and put out a message on the shell giving some indication of what statement caused the error “ Traceback ” …
E N D
Exceptions in Python Error Handling
Error handling • What happens when a Python rogram is running and an error occurs? • Python IDEs will “catch” the error signal and put out a message on the shell giving some indication of what statement caused the error • “Traceback” … • It is possible to handle your own errors so you don’t get this message
Checking for Error conditions • A lot of error checking is done with if (else) statements • making sure a number is not negative before you take the square root of it • making sure the number is not zero before you divide by it • Some errors are hard to detect this way • trying to open a file
Exceptions • Most modern languages have some way to let the programmer specify what should happen if a particular error occurs while the program runs • The error signal is usually called “an exception” (as in “exception to the rule”) • In C++ they use “try” and “catch” • In Python they use “try” and “except”
Try / Except • The syntax uses two new keywords • example try: sq_x = sqrt(x) except ValueError: print(“a negative number for sqrt”) sq_x = 0
Semantics • The “try block” is executed – a process in the background is watching for the error signal (exception) • If the try block succeeds (no exception), the except: block is skipped and execution proceeds from the next line after the except block • If the try block raises an exception, the except block for that particular exception is executed and then execution continues • If you don’t have one for that error, the except block is skipped and the usual IDE error handling takes over
Notes • The common errors to catch • ZeroDivisionError • ValueError (wrong value used) • TypeError (wrong type used) • IndexError (for subscripts) • IOError (for files) • Keep the “try block” as small and focused as possible. This makes it easier to handle the one or two errors which could happen.
Notes • You can have several except blocks for one try block, each one catching a different error. • If a try block raises more than one exception, the first except block that matches is the ONE that is done (it does not keep looking through the list for more)