【发布时间】:2021-09-27 21:53:10
【问题描述】:
我正在尝试正确处理异常,所以我一直在试验这段代码:
class MainClass
{
private static Logger logger = new Logger();
public static void Main(string[] args)
{
try
{
Method1("");
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
private static void Method1(string text)
{
try
{
Method2(text);
}
catch (Exception ex)
{
logger.Write(ex);
throw ex;
}
}
private static void Method2(string text)
{
try
{
Console.WriteLine(text[0]);
}
catch (Exception ex)
{
logger.Write(ex);
throw;
}
}
}
我注意到在Method2中记录的异常,它表明在try块中抛出了错误:"Console.WriteLine(text[0])":
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at ExceptionHandlingTest.MainClass.Method2 (System.String text) [0x00002] in /ExceptionHandlingTest/Program.cs:40
但是在Method1记录的异常中,只显示在catch块中被抛出:throw;:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at ExceptionHandlingTest.MainClass.Method2 (System.String text) [0x00020] in /ExceptionHandlingTest/Program.cs:45
at ExceptionHandlingTest.MainClass.Method1 (System.String text) [0x00002] in //ExceptionHandlingTest/Program.cs:26
我在这里做错了什么,还是它应该工作的方式?当我进入 Method1 时,InnerException 为 null。
我看到如果我从 Method2 中删除 try/catch,Method1 中的异常会在 Console.WriteLine 中出现我所期望的错误。我想这让我想知道:我如何确定在哪里/何时处理异常?似乎越早越好。
【问题讨论】:
-
是的,阅读important box。
-
这就是我感到困惑的地方,因为在 Method2 中我只是使用
throw;而在 Method1 中在执行throw ex;之前立即记录异常