Loading lessons...
Try...Except Advanced
Try...Except Advanced
Many exceptions can be raised together, and there are extra blocks: else and finally.
Raise multiple exceptions
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
The first matching except runs.
Raise one exception
You can catch several types in one tuple:
try:
x = int("not a number")
except (ValueError, TypeError):
print("Bad value or type")
else
Runs only if NO exception happened:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
finally
Runs whether or not an exception occurred:
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Use finally for cleanup, like closing files.
Raise your own exceptions
raise throws an error on purpose:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Custom exception types
class MyError(Exception):
pass
raise MyError("custom problem")
TL;DR
- Multiple except blocks handle different errors.
- else runs on success; finally always runs.
raisethrows your own errors.- Custom exceptions subclass Exception.