vendredi 17 septembre 2021

how to handle exception in a better way [closed]

I am new to python and I do not know the best practices, hence the question on knowing a better way.

In this program, the output of one function is the input to other.

Like this

from random import randrange

def op_1():
    if randrange(2) % 2:
        raise Exception('Unhandled exception occurred in 1')
    return 1

def op_2(a):
    if randrange(2) % 2:
        raise Exception('Unhandled exception occurred in 2')
    return a + 2

def op_3(b):
    if randrange(2) % 2:
        raise Exception('Unhandled exception occurred in 3')
    return b + 3

try:
    print(op_3(op_2(op_1())))
except Exception as e:
    print(e)

Output of op_1 is the input to op_2, whose output will be the input to op_3.

In case an unhandled exception occurs I want to log it and exit the program.

Aucun commentaire:

Enregistrer un commentaire