Python try except else
The "try-except-else" statement in Python allows you to handle exceptions in your code in a more controlled way.
Here is an example:
try:
# code block that may raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
# code block to handle the specific exception
print("Cannot divide by zero!")
else:
# code block that is executed if no exception occurs
print("Division completed successfully!")
print("Result:", result)
In this example, the code block inside the "try" statement attempts to divide 10 by 0, which will raise a ZeroDivisionError. This error is caught by the corresponding "except" block, which displays an error message. If no exception occurs, the code block inside the "else" statement is executed, displaying a success message along with the result of the division.
Using the "try-except-else" statement allows you to separate the error handling logic from the normal flow of your code, making it easier to write more robust programs.