如何在c#中检测异常源?

如何在c#中检测异常源?,c#,exception,exception-handling,C#,Exception,Exception Handling,这是一个在我脑海中提出这个问题的例子。我有一个try块,其中包含Convert.ToInt32和DateTime.ParseExact方法调用。捕获FormatException时,如何检测引发异常的方法 示例代码: try { //mStrToDate and mStrToInt are the variables that contains desired time and integer values in string format DateTime myDate = D

这是一个在我脑海中提出这个问题的例子。我有一个try块,其中包含
Convert.ToInt32
DateTime.ParseExact
方法调用。捕获FormatException时,如何检测引发异常的方法

示例代码:

try
{
    //mStrToDate and mStrToInt are the variables that contains desired time and integer values in string format
    DateTime myDate = DateTime.ParseExact(mStrToDate, "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture);
    int mIntVar = Convert.ToInt32(mStrToInt);
}
catch (FormatException exc)
{
    Console.WriteLine(exc.Message);//this line must specify the exception source 
}

如果您想这样做,如果您知道两条语句都会抛出与示例中相同的异常,您应该使用不同的try-catch块

try
{
    DateTime myDate = DateTime.ParseExact(mStrToDate, "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture);
}
catch (FormatException exc)
{
    Console.WriteLine("Exception from DateTime.Parse" + exc.Message);
}

try
{
    int mIntVar = Convert.ToInt32(mStrToInt);
}
catch (FormatException exc)
{
    Console.WriteLine("Exception from Convert.ToInt32 " + exc.Message);
}
您可以编写某种包装器,在给定调用(操作)列表的情况下,它将在try-catch块中执行操作。这将有助于解决(或改善)在大量通话中干净利落地执行所有这些操作的问题


其他办法: 异常消息中的挖掘信息

在某些情况下,消息本身可能包含一些信息,但使用字符串消息的假设部分对结果进行分类并推断其来源似乎很难闻

如果识别异常源对您很重要,那么您不应该依赖于某些消息行为,这些行为可能会在未经通知的情况下更改并破坏您的代码

从异常堆栈跟踪挖掘信息

调用堆栈可以使用,对我来说似乎更可靠,但要复杂得多。但这对你的案子应该有用

不要使用异常

正如在评论中多次提到的,有一种“tryParse”方法,它可能以更好的方式解决您的问题如果预计parsings有时会失败,那么也不例外。


这是您正常程序流程的一部分,您应该这样对待它(使用try parse和条件逻辑,具体取决于解析的成功)

与我的示例类似,您的问题可能有用

try
    {
        //mStrToDate and mStrToInt are the variables that contains desired time and integer values in string format
        DateTime myDate = DateTime.ParseExact(mStrToDate, "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture);
        //int mIntVar = Convert.ToInt32(mStrToInt);

        string line = Console.ReadLine();
        if (!int.TryParse(line, out mIntVar ))
        {
            Console.WriteLine("{0} is not an integer", line);
            // Whatever
        }

    }
    catch (FormatException exc)
    {
        Console.WriteLine(exc.Message);//this line must specify the exception source 
    }    
或者你也可以使用这个简单的代码

string line = Console.ReadLine();
int mIntVar ;
if (!int.TryParse(line, out mIntVar ))
{
    throw new FormatException();
}
方法获取发生错误的位置

    public static string MethodWhereExceptionOccured(Exception ex)
    {
        return ex.StackTrace.Split('\r').First().Trim();
    }

为每个函数使用不同的try-catch块,或者使用
TryParseExact
int.TryParse
而不是捕获异常。这就是
TryParse*
方法的用途。例外应该是例外。无效输入不是异常,应该避免抛出异常。我不明白?StackTrace已经准确地告诉您异常发生在哪个方法中?@GerriePretorius创建自定义异常类将解决此问题。使用StackTrace detail,我将检测从FormatException继承的异常中的异常源。然后我用这个自定义异常类捕获异常。感谢您展示我错过的关于StackTrace的关键点。@BobGeiger这里C#7的具体内容是什么?@BobGeiger。不是c#7,我使用c#5(.NET Framework v4.5)我成功构建的,如果你有邮件地址,我会发送给你capture@BobGeiger
    public static string MethodWhereExceptionOccured(Exception ex)
    {
        return ex.StackTrace.Split('\r').First().Trim();
    }