try:
print("Doing something")
except:
print("Something went wrong")
try:
print("Doing something")
except BaseException as e:
print("Something went wrong: " + str(e))
try:
print("Doing something")
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Catching specific errors
See the different exception types here
try:
print("Doing something")
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
If no errors occurred
You can use the else keyword to define a block of code to be executed if no errors were raised:
try:
print("Doing something")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Raising an error
raise
raise Exception("Sorry, no numbers below zero")
raise TypeError("Only integers are allowed")
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.