xxxxxxxxxx
try:
#Code to execute
except Exception as err:
print(f"{type(err).__name__} was raised: {err}")
xxxxxxxxxx
try:
someFunction()
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print (message)
xxxxxxxxxx
>>> try:
raise Exception('spam', 'eggs')
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
# but may be overridden in exception subclasses
x, y = inst.args # unpack args
print('x =', x)
print('y =', y)
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
xxxxxxxxxx
try:
# Some code that may raise an exception
except Exception as e:
print("An error occurred:", str(e))