Python Exception Exception
Example
Raise an exception with your own message:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Try it Yourself »
Definition and Usage
The Exception class is the base class for most built-in exceptions. Errors like TypeError, ValueError and ZeroDivisionError all inherit from it.
You can use raise Exception() to create your own error, with a message that explains what went wrong.
If you use except Exception in a try...except statement, you catch almost every error, see the example below.
Note: SystemExit, KeyboardInterrupt and GeneratorExit do not inherit from Exception, so except Exception does not catch them.
Exception Handling
Example
Catch any error with except Exception:
try:
x = 1 / 0
except Exception as e:
print("Something went wrong:", e)
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.