1

I have a code for a function which is called inside another function.(Result of refactoring).

So in the called function I have a huge block of try-catch statements as.

def Called():
     try:
         #All statements for the function in the try block.
     except A:
         # Exception handler.
     except B:
         # Exception handler.
     except A: 
         # Exception handler.

The problem I have is that I need to catch two exceptions of the same type (At different locations in the Called function). Which then are handled by the Calling function.

One way would be to define two try-except blocks within the Called function. But I am not understanding how the Calling function can handle two exceptions of the same type differently.

veepsk
  • 1,703
  • 3
  • 14
  • 21

2 Answers2

3

This won't work as advertised; only the first except A clause will ever get executed. What you need is either some logic inside the clause to further inspect the exception, or (if the code inside the try block permits) several try-except blocks.

Example of the former approach:

try:
    something_that_might_fail()
except A as e:
    if e.is_harmless():
        pass
    elif e.is_something_we_can_handle():
        handle_it()
    else:
        raise    # re-raise in the hope it gets handled further up the stack
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0

I think this will work

def Called():
     try:
         #All statements for the function in the try block.
     except A:
         try: 
             do_someting()
         except B:
             try:
                do_somthing_else()
             except:

     except A: 
         # Exception handler.
Sociopath
  • 13,068
  • 19
  • 47
  • 75