throw exception to another exception in one def using python

Question:

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():
try:
   # some file running code
   try:
      # Code For Calculation
   Except Exception as E:
      Print(E)
      raise Exception from E
   # sendEmail(user,E)     # Send email if calculation successful
Except Exception as E:
   print(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

||

Answers:

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:
        pass
    else:
        raise Exception('Error from someFileRunningCode')
    
def codeForCalculation(err):
    if not err:
        pass
    else:
        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):
    someFileRunningCode(err_fr)
    try:
        codeForCalculation(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]))
        try:
            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()))
        finally:
            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

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

outputs

outer bar
inner foo
Answered By: chepner