注册事件AppDomain.FirstChanceException.
在实际抛出之前,您会看到所有异常。在事件处理程序中,您可以检查您的exception
并执行所需的日志记录。
没有魔力和没有坏设计。
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
DoBadThings();
}
private static void DoBadThings()
{
DoOneLevelBelow();
}
private static void DoOneLevelBelow()
{
for(int i=0;i<10;i++)
{
try
{
if (i == 5)
{
var invalidCast = (string)((object)i);
}
else
{
throw new InvalidTimeZoneException();
}
}
catch
{
}
}
}
static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
if(e.Exception is InvalidCastException)
{
LogInvalidCast((InvalidCastException)e.Exception);
}
}
private static void LogInvalidCast(InvalidCastException invalidCastException)
{
Console.WriteLine("Got Invalid cast: {0}", invalidCastException);
}
这将导致:
得到无效的转换:System.InvalidCastException:
类型 "System.Int32"
不能转换到 “System.String” 的对象。在 ThrowTest.Program.DoOneLevelBelow()
在 d:\媒体\博客\ ThrowTest \的Program.cs:行31
请注意,因为你得到异常的堆栈展开之前,你会看到只有方法在那里确实发生了但没有调用方法,因为堆栈还没有被解开。 如果您想要完整的调用堆栈,则可以使用Environment.StackTrace
来获取所有堆栈帧。
它有什么用处? – 2015-02-08 13:15:06
关键字不可覆盖也不可重载。 – 2015-02-08 14:59:46
另外,如果你可以重写抛出,你可以看到底层库的一些意想不到的结果。 :) – eandersson 2015-02-09 00:25:25