Note that there are some explanatory texts on larger screens.

plurals
  1. POI want to return a value AND raise an exception, does this mean I'm doing something wrong?
    primarykey
    data
    text
    <p>I have a number of functions that parse data from files, usually returning a list of results.</p> <p>If I encounter a dodgy line in the file, I want to soldier on and process the valid lines, and return them. But I also want to report the error to the calling function. The reason I want to report it is so that the calling function can notify the user that the file needs looking at. I don't want to start doing GUI things in the parse function, as that seems to be a big violation of separation of concerns. The parse function does not have access to the console I'm writing error messages to anyway.</p> <p>This leaves me wanting to return the successful data, but also raise an exception because of the error, which clearly I can't do.</p> <p>Consider this code:</p> <pre><code>try: parseResult = parse(myFile) except MyErrorClass, e: HandleErrorsSomehow(str(e)) def parse(file): #file is a list of lines from an actual file err = False result = [] for lines in file: processedLine = Process(line) if not processedLine: err = True else result.append(processedLine) return result if err: raise MyErrorClass("Something went wrong") </code></pre> <p>Obviously the last three lines make no sense, but I can't figure out a nice way to do this. I guess I could do <code>return (err, result)</code>, and call it like</p> <pre><code>parseErr, parseResult = parse(file) if parseErr: HandleErrorsSomehow() </code></pre> <p>But returning error codes seems un-pythonic enough, let alone returning tuples of error codes and actual result values.</p> <p>The fact that I feel like I want to do something so strange in an application that shouldn't really be terribly complicated, is making me think I'm probably doing something wrong. Is there a better solution to this problem? Or is there some way that I can use <code>finally</code> to return a value and raise an exception at the same time?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload