Tuesday, 13 November 2018

Handling multiple exceptions in functions

I have a tiny web-server written in Python 3 using http.server which calls the function translate() in method do_GET() like this:

class httpd(BaseHTTPRequestHandler):
    def do_GET(self):
        self.wfile.write(bytes(f'{translate(var[0])}', 'utf-8'))

Now in this translate() function I have several conditional statements and try and except blocks roughly like this:

def translate(param):
    try:
        # do something
    except SomeError as some_err:
        print("Error: " % some_err)
        return ""

    if True:
        try:
            # do something
        except SomeOtherError as some_other_err:
            print("Error: " % some_other_err)
            return ""
        except SomeThirdError as some_third_err:
            print("Third error: " % some_third_err)
            return ""
    else:
        # additional try and except blocks which print an error and
        # return an empty string

The code above is simplified, but in principle I return an empty string if an exception happens and thus my web server returns nothing to client if an exception happens.

Is there a more manageable way to handle this? Specifically, I'm looking to:

  • Avoid catching each error via a separate except section, while still supporting an error message dependent on error type.
  • Avoid writing multiple try / except statements, often nested, within my function.

Note: This is a copy of this now deleted question. The solution from that post is included below, but other answers are welcome.



from Handling multiple exceptions in functions

No comments:

Post a Comment