Skip to content

Files

62 lines (39 loc) · 2.41 KB

Python_Manage_exception_with_try_except.md

File metadata and controls

62 lines (39 loc) · 2.41 KB



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:

Input

Setup Variables

  • numérator: is the numerator of the division
  • denominator: is the denominator of the division
numerator = 10
denominator = 0

Model

Try Except example

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")

Output

Display result

print("Result:", result)