Tutorial by Examples

If your code encounters a condition it doesn't know how to handle, such as an incorrect parameter, it should raise the appropriate exception. def even_the_odds(odds): if odds % 2 != 1: raise ValueError("Did not get an odd number") return odds + 1
Use try...except: to catch exceptions. You should specify as precise an exception as you can: try: x = 5 / 0 except ZeroDivisionError as e: # `e` is the exception object print("Got a divide by zero! The exception was:", e) # handle exceptional case x = 0 final...
Sometimes, you may want something to occur regardless of whatever exception happened, for example, if you have to clean up some resources. The finally block of a try clause will happen regardless of whether any exceptions were raised. resource = allocate_some_expensive_resource() try: do_stu...
Sometimes you want to catch an exception just to inspect it, e.g. for logging purposes. After the inspection, you want the exception to continue propagating as it did before. In this case, simply use the raise statement with no parameters. try: 5 / 0 except ZeroDivisionError: print(&quo...
In the process of handling an exception, you may want to raise another exception. For example, if you get an IOError while reading from a file, you may want to raise an application-specific error to present to the users of your library, instead. Python 3.x3.0 You can chain exceptions to show how t...
Exception handling occurs based on an exception hierarchy, determined by the inheritance structure of the exception classes. For example, IOError and OSError are both subclasses of EnvironmentError. Code that catches an IOError will not catch an OSError. However, code that catches an EnvironmentErr...
Exceptions are just regular Python objects that inherit from the built-in BaseException. A Python script can use the raise statement to interrupt execution, causing Python to print a stack trace of the call stack at that point and a representation of the exception instance. For example: >>&gt...
Create a class inheriting from Exception: class FooException(Exception): pass try: raise FooException("insert description here") except FooException: print("A FooException was raised.") or another exception type: class NegativeError(ValueError): pass ...
While it's often tempting to catch every Exception: try: very_difficult_function() except Exception: # log / try to reconnect / exit gratiously finally: print "The END" # it runs no matter what execute. Or even everything (that includes BaseException and all its c...
There are a few ways to catch multiple exceptions. The first is by creating a tuple of the exception types you wish to catch and handle in the same manner. This example will cause the code to ignore KeyError and AttributeError exceptions. try: d = {} a = d[1] b = d.non_existing_fiel...
User input Imagine you want a user to enter a number via input. You want to ensure that the input is a number. You can use try/except for this: Python 3.x3.0 while True: try: nb = int(input('Enter a number: ')) break except ValueError: print('This is not a num...
Code in an else block will only be run if no exceptions were raised by the code in the try block. This is useful if you have some code you don’t want to run if an exception is thrown, but you don’t want exceptions thrown by that code to be caught. For example: try: data = {1: 'one', 2: 'two'}...

Page 1 of 1