Search code examples
pythonerror-handlingnestedtry-except

Error Handling in Nested try-except in python


The piece of code i have looks like this:

try:
    funcProneToError()
    #codeBlock1
except:
    #errorMessage

def funcProneToError():
    try:
       #raise error
    except:
       #erorMessage

Now the problem is that if an error is raised in funcProneToError(), the code skips codeBlock1 and prints error message twice. is there any way to bypass this? iwant to be able to run codeblock1 even if an error is detected in the function.

Also im coming here after a really long time so ignore any formatting mishaps.


Solution

  • try:
        funcProneToError()
    except:
        #errorMessage
    finally:
        #codeBlock1
    
    def funcProneToError():
        try:
           #raise error
    

    (1) Your code handles the exception twice therefore the error message is printed twice.

    Remove the except block in funcProneToError(). funcProneToError() raises an exception and this exception is handled (only once) after the function has been called.

    (2) Use a 'finally' block so that codeBlock1 prints regardless of whether there was an exception raised.

    I hope this helps! :)