简体   繁体   中英

Exception thrown by a function, where that function called when exception thrown in it

I have a function "ReturnString":

public static string ReturnString(string sa, string sb)
{
 try
 {
  ...
  ...
  return "xyz";
 }
 catch (Exception ex)
 {
  throw new clsException(ex.Message);
 }
}

it is call by more than 600 times from other more then 40 classes and win farms Mean's it has more than 600 references in more then 40 classes and win farms.

When Exception thrown by it, I want to know what is the it's last calling ref. when exception happen? Please help me to solve this without changing function arguments.

I want to know what is the it's last calling ref. when exception happen?

Then check the exception StackTrace , that will let you know the entire call stack and the latest one responsible for exception. Also the innerException property if any.

Check the documentation on Exception class. It has a property StackTrace which you should check.

In your case, the exception object should have it ex.StackTrace

You may also want to get the TargetSite property value from your exception object saying ex.TargetSite

Your problem is here:

throw new clsException(ex.Message);

As others have mentioned, ex already contains the info you want inside the StackTrace property (check this link for more info).

But when you throw a new exception, you are only throwing the message, and ignoring all the info you want to get.

Just throw without a new exception, or include ex as the inner exception of your clsException .

You should initialize an instance of StackTrace class -

https://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace(v=vs.110).aspx

Then, get the first StackFrame -

https://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe(v=vs.110).aspx

Finally, get the MethodBase of this frame; Its "Name" property is what you need -

https://msdn.microsoft.com/en-us/library/system.reflection.methodbase(v=vs.110).aspx

Try this:

    public static string ReturnString(string sa, string sb)
    {
        try
        {
            //...
            //...
            return "xyz";
        }
        catch (Exception ex)
        {
            StackTrace oStackTrace = new StackTrace();
            string sMethodName = oStackTrace.GetFrame(1).GetMethod().Name;
            //It's not a good practice to keep only the error message (you may need other exception details later)
            throw new clsException(string.Format("{0}: {1}", sMethodName, ex.Message));
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM