.net中的异常处理

-1 c# exception

我捕获了一个异常,在捕获之后我必须附加方法名称,以便我知道错误来自哪个方法,然后将其抛给另一个函数并将其保存在数据库中.

try
{
}
catch (Exception ex)
{
    string strError = ex.Message.ToString() + "methodname:getNoOfRecordsForBatchProcess";
    throw strError.ToString();
}  
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误,你不能使用字符串变量来抛出异常.抛出异常仅用于系统异常.有没有办法处理这个错误.

Tig*_*ran 5

方法名称也在Exception.StackTrace属性中可见.

顺便说一句,您可以依赖其他方式使用StackFrame类恢复其名称,例如:

        private static string GetCallingMethodName()
        {
            const int iCallDeepness = 2; //DEEPNESS VALUE, MAY CHANGE IT BASED ON YOUR NEEDS
            System.Diagnostics.StackTrace stack = new System.Diagnostics.StackTrace(false);
            System.Diagnostics.StackFrame sframe = stack.GetFrame(iCallDeepness);
            return sframe.GetMethod().Name;
        }
Run Code Online (Sandbox Code Playgroud)