Python - Try Except

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.

Exception handling

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: 
print(x)
except:
print("Exception display here")
Without the try the program spits out and stops.

Handling Multiple Exceptions

Multiple blocks can be defined for each exception exept depending on the type of error you want to handle.

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("An error occurred")

Else

The keywordelse executes if none of the exceptions are raised.

try:
print("Hello")
except:
print("Error")
else:
print("Everything is fine")

Finally

The Finally block executes regardless of whether there is an error or not.

try:
print("Hello")
except:
print("Error")
finally:
print("runs in all cases")

Raise

If a condition occurs, Python programmers have the option to handle an exception.

Use the keyword raise to handle an exception.

x=-2
if x < 0:
raise Exception("x is less than zero")