throw exception to another exception in one def using python


I’ve function to calculate data and after successful calculation the mail has been send to user. but now I want to do error mapping for user interface to show error to users, so that they understand where exactly the error is getting, In their data or in my system.

So I’m Trying below Code:

def calculateFleet():
   # some file running code
      # Code For Calculation
   Except Exception as E:
      raise Exception from E
   # sendEmail(user,E)     # Send email if calculation successful
Except Exception as E:
   # sendEmail(user,E)     # Send email if any error occured

I want to throw the one exception to another exception. like given in an image:
enter image description here

How can I pass/raise/throw an exception to another exception?

Thanks In advance!!

Asked By: Namita Tare



Hi Namita, I find your question a little bit unclear.
I try to answer the so that they understand where exactly the error is getting part. To achieve this, you can think of sending the whole traceback using the traceback module.

import traceback
import sys

import itertools

def someFileRunningCode(err):
    if not err:
        raise Exception('Error from someFileRunningCode')
def codeForCalculation(err):
    if not err:
        raise Exception('Error from codeForCalculation')

def sendEmail(user, email):
    print('To: {usr}n{text}n'.format(usr = user, text = email))
def calculateFleet(err_fr, err_cc):
    except Exception as E:
        raise Exception(E) from E

if __name__ == '__main__':
    user = '[email protected]'  # mock user email
    for err in itertools.product((True, False), repeat = 2):
        msg = ['OK' if not e else 'ERROR' for e in err]
        print('- file running: {}n- calculation: {}'.format(msg[0], msg[1]))
            calculateFleet(err[0], err[1])
            email = 'Everything ok, here are the results.'
        except Exception as E:
            email = ('Something went wrong while processing your data,' 
                     + 'here is the traceback:n {}'.format(traceback.format_exc()))
            sendEmail(user, email)

In the above example, the main loop explores all the possible combinations of failures for the case at hand and the sendEmail function allows you to have a print preview of what the user will receive in the email body.

If this does not fulfill your needs, please provide a clearer example of the expected output (e.g. error in someFileRunningCode –> message to be displayed…).

Answered By: Luca

As you are using raise Exception from E, then the "outer" exception will have the "inner" exception as its __cause__ attribute. The following

        raise Exception("foo")
    except Exception as e:
        raise Exception("bar") from e
except Exception as e:
    print("outer", e)
    print("inner", e.__cause__)


outer bar
inner foo
Answered By: chepner