When an error occurs, or exception as we call it, Python will normally stop and generate an error message.These exceptions can be handled using the try statement:
Example
The try block will generate an exception because x is not defined:
try:
print(x)
except:
print("An exception occurred")
You can use the else keyword to define a block of code to be executed if no errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
An else clause will execute if there were no errors, and by not executing that code in the try block, you avoid catching an unexpected error. Again, catching an unexpected error can hide bugs.