yeswekhan
yeswekhan

Reputation: 15

Handling an error within an exception in Python 2?

I have code that will draw an exception like so:

try:
    causeEitherError1orError2
except Error1:
    handle Error1
    cause Error2
except Error2:
    handle Error2

Trying action A causes either Error1 or Error2. Handling Error1 sometimes causes Error2. How can I handle both Error1 and Error2, when Error2 can be caused by the original try or by Error 1?

Upvotes: 1

Views: 387

Answers (4)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21474

if the entire block of try: .. except Error1: can all raise Error2 then that entire try except should be inside another try:

try:
    try:
        causeEitherError1orError2
    except Error1:
        handle Error1
        cause Error2
except Error2:
    handle Error2

This way both errors can be raised and caught correctly.

Upvotes: 1

cs95
cs95

Reputation: 403128

In general, this seems like a convoluted design, but you do have the ability to catch multiple exceptions with one except brace. You can also nest try-except handlers to your advantage. One possible design would be:

try:
    ... # action A
except (Error1, Error2) as e:
    try:
        ... # handle e
    except Error2 as f:
        ... # handle f

If you want to discern what Exception was raised the first time, you can always check the type:

print(type(e)) # prints Error1 or Error2 depending on what was raised

Or, more accurately, narrow it down with an isinstance check:

if isinstance(e, Error1):
    ... # handle e as Error1
else:
    ... # handle e as Error2

Upvotes: 3

camoverride
camoverride

Reputation: 21

This seems like a weird situation, but I could imagine something like this being necessary when handling network requests. You can try a structure like this:

try:
    causeEitherError1orError2
except (Error1, Error2) as e:
    try:
        handle e
    except Error2 as q:
        handle q

Upvotes: -1

zimmerrol
zimmerrol

Reputation: 4951

I don't think that your error handlers should even be causing errors again. This seems to be a strange design. Nevertheless, you could solve the issue by declaring a function which is taking care of every error and might be calling it self iteratively. But this will cause a massive problem: imaging if you are calling your function, error-type 1 is caused, it is handled and during this error 2 is raised. The handling of this is causing a type 1 error again, and so on. You will get a stack overflow as there is no end.

You could add some kind of error-level counter to you global error-level for function, which is increased by raising an error inside an error handler. Then you could add some kind of limit, at which the error handling will just be stopped.

Upvotes: 2

Related Questions