Reputation: 482
In my python code, I would like to catch all the errors & display an error message. For example, I would like to do this thing
try:
my code block
catch:
print("Error:x error occurred" )
Can you suggest me how to do this?
Upvotes: -1
Views: 58
Reputation: 22776
If you're interested in the exception type, then you can catch all exceptions using except Exception as ex
(ex
can be anything), and then get the exception type using type(ex).__name__
:
try:
# example, dividing by zero
x = 1 / 0
except Exception as ex:
print("Error: {} error occurred".format(type(ex).__name__))
Output:
Error: ZeroDivisionError error occurred
If the type doesn't matter, then this will do:
try:
# some code
except:
print("Error:an error occurred") # any error, but you don't know which
Upvotes: 2