You can check a block of code for errors with the try.
You can handle the error by using the except.
When there are no errors, you can run code using the else.
Regardless of the result of the blocks try and except, you can still run code using the finally.
In the event of an error, or an exception as we call it, Python will often terminate and produce an error message.
The statement try can be used to handle some exceptions.
Example:
An exception will occur because the variable x is not set.
try:Without the try the program spits out and stops.
print(x)
except:
print("Exception display here")
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("An error occurred")
try:
print("Hello")
except:
print("Error")
else:
print("Everything is fine")
try:
print("Hello")
except:
print("Error")
finally:
print("runs in all cases")
x=-2
if x < 0:
raise Exception("x is less than zero")
Please disable your ad blocker and refresh the window to use this website.