1

In Python, can I use try and except when calling functions from my core function, and error checking that the called functions are succeeding? Is this a good way to structure your script with the core function calling functions and sandwiching them in try/except statements to manage errors? If the called functions throw an error or a False, will the try in the core function manage that?

def core_function():

    try:
        function_a()
    except_Exception as e:
        print(e)

    try:
        function_b()
    except Exception as E:
        print(e)


def function_a()
    #this will error
    print 1 + 'a'
    return True

def function_b()
    print 1 + 1
    return True
winteralfs
  • 459
  • 6
  • 25

1 Answers1

2

If the called functions throw an error or a False, will the try in the core function manage that

There are basically two ways a function can report an error. By returning something that indicates an error or by raiseing an exception. try catch block in Python handles the latter. You can do something like that.

def core_function():

    try:
        if function_a() == False:
            raise Exception('function_a failed')
        if function_b() == False:
            raise Exception('function_b failed')

    except Exception as E:
        print(e)

Read this for Conventions for error reporting: Exceptions vs returning error codes

abhiarora
  • 9,743
  • 5
  • 32
  • 57
  • thanks, this is helpful. Would you sandwich all your function calls from the core function inside a try catch block as standard practice, or just the risky ones? – winteralfs Jul 20 '20 at 03:59
  • 1
    I would prefer all be part of the `try catch` block. – abhiarora Jul 20 '20 at 04:00
  • I have read that try blocks should be kept simple and not hold multiple things. and this workflow does seem to violate that, but I do like the idea of working this way. – winteralfs Jul 20 '20 at 04:04
  • It's just safe to put function in try catch if they might throw an error. Using the above approach have one benefit of having error handling code at a single place which basically help with readability. – abhiarora Jul 20 '20 at 04:17