else
` keyword to define a block of code to be executed if no errors were raised :try:
# Your code goes here
except Exception as e:
print(f"An error occurred: {e}")
else:
print("No errors were raised")
try
` block contains the code that you want to execute. If an error occurs, the program will jump to the `except
` block and execute the code inside it. If no errors occur, the program will execute the code in the `else
` block.try:
x = 10
y = 5
z = x / y
except ZeroDivisionError as e:
print("Cannot divide by zero")
except Exception as e:
print(f"An error occurred: {e}")
else:
print(f"The result is {z}")
The result is 2.0
x / y
` operation is valid, and it returns the result of 2.0. Since no errors occurred, the program executes the code in the `else
` block and prints the result.y
` was set to zero, then the program would raise a `ZeroDivisionError
` exception, and the code in the `except
` block would be executed instead.