except - Used with exceptions, what to do when an exception occurs
except keyword is used in conjunction with the
try keyword and often the
finally keyword. It lets you define a code block that handles exceptions.
try: result = 10 / 0 except: print("Oops - division by 0!")
Oops - division by 0!
Specific exceptions can be caught as well.
def divide(n, d): try: result = n / d except ZeroDivisionError: # return positive infinity result = float('inf') return result result = divide(10, 0) print(result)
You can specify more than one exception type as well as the general exception handler at the end. For example:
except SomeException: # handler except SomeOtherException: # handler except: # if anything else
Notes: Where to put the
except handler is something to be carefully considered because the exception might occur deep inside nested functions, which means that the code has to have
except handlers in possibly many places.
To capture the text of an exception, use this form:
except Exception as e: # Log the message print(e)