简体   繁体   中英

what is the correct way to handle a caught exception and raise it outside of try block

Im just starting my python learning journey and need some help with the correct way to raise an exception.

Consider a block of code which loops thru a list and performs a task. If an exception occurs,continue with the program execution. And execute the rest of the code. At the end of the program raise the exception and system the application with non zero code. The idea is the program should continue executing all the tasks, but exit with a non 0 code for an external application to track and report.

save_exc_info = None

def numMatcher(numbers):
    try:
        if numbers != 2:

            print('number match ' + str(numbers))

        else:
            raise ValueError('Number not in list. Will be logged for troubleshooting')  # raise exception and log it

    except ValueError as veer:  # exception 1 caught and saved
        save_exc_info = sys.exc_info()


    except (IOError, OSError) as ioerr:  # exception 2 caught and saved
        save_exc_info = sys.exc_info()


try:
    print('Next step')  # Perform rest of the tasks in the code

except Exception as excp:  # exception 3 caught and saved
    save_exc_info = sys.exc_info()

print('final step')

numlist = [1, 2, 3]

for numbers in numlist:
    numMatcher(numbers)

if save_exc_info is not None:
    traceback.print_exception(*save_exc_info)  # how to return the right exception and print?
    sys.exit(1)  # At the end of the program, exit with non zero code as there was an exception in the program.

When handling the exception, you can assign it to a variable, eg:

    except AssertionError as aerr:
        saved_exception = aerr

Which you can later access eg:

print(saved_exception)

For you code, this gives you an option of not having two variable, and instead of isError just use saved_exception = None and later test if saved_exception is not None: ...

Not sure how useful saving exception for later (using it as general interface to pass information around) is. Perhaps it may be worth rethinking a bit more.

N Chauhan also made a good point int the comment about AssertionError not being very suitable exception to use to convey this type of information.


To your updated question. If you want to print the traceback is you'd see it when the exception was raised, probably the most straightforward would be to save exception information and use print_exception() (or its format_exception friend):

except ValueError:
    save_exc_info = sys.exc_info()            
...
traceback.print_exception(*save_exc_info) 

You could have extracted the same information from / use the saved exception as well, *save_exc_info could have also been: type(saved_exception), saved_exception, saved_exception.__traceback__ (for the saved exception in the first example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM