Template request | Bug report | Generate Data Product
Tags: #python #error #try #exception #snippet
Author: Benjamin Filly
Description: This notebook will demonstrate how to manage code error using try except.
The try
block lets you test a block of code for errors.
The except
block lets you handle the error. You can specify the type of exception to manage error.
The else
block lets you execute code when there is no error.
The finally
block lets you execute code, regardless of the result of the try- and except blocks.
References:
numérator
: is the numerator of the divisiondenominator
: is the denominator of the division
numerator = 10
denominator = 0
In this case, We divide numerator
by the denominator
and we cannot divide the numerator by 0, so we get an error but we can handle it with except
.
The else
block lets you execute code when there is no error and the finally
block lets you execute code, regardless of the result of the try- and except blocks.
try:
result = numerator / denominator
except Exception as e:
result = f"Exception error: {e}"
print(result)
else:
print("Nothing went wrong")
finally:
print("The bloc `finally` is executed anyway")
print("Result:", result)