简体   繁体   中英

code is cluttered by try-except in Python

I have a series of processes to run on bunch of texts. The process it may fail in whatever reasons.

If I want to record the failure of each process, Should I use try-except clause? The problem is my code is overwhelmed with try-except,the main flow of processes is cut to pieces.

for path in paths:
    with open(path) as file:
        text=file.read()
        try:
            process1(text)
        except Exception as e:
            handle e
            record_failure( process1 , file.name)
            continue

        try:
            process2(text)
        except Exception as e:
            handle e
            record_failure( process2 , file.name)
            continue
        .
        .
        .
        processN

Or Should I afterward analyze that at exception log file, that's not easy I think.

Is there better way to tackle this?

You could put all your processes in a loop:

allProcs = [process1, process2, processN]

for path in paths:
    with open(path) as file:
        text=file.read()
        for proc in allProcs:
            try:
                proc(text)
            except Exception as e:
                # handle e
                record_failure( proc , file.name)
                continue

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