问题描述
基于
异常过滤的优点更多是与过滤器不匹配有关,而不是与过滤器不匹配有关.如果删除除第一个块以外的所有 catch
块,然后将第一个 catch
块上的过滤器更改为 when(e.code!= 0)
,则异常的调用堆栈将表明它已在第16行引发.
实现此目标的旧方法如下:
试试{抛出新的specialException();//第16行抛出新的Exception("Weird exception");//int a = Int32.Parse("fail");}捕获(specialException e){if(e.code!= 0){WriteLine("E.code不为0");返回;}扔;}
在这种情况下,调用堆栈将指示该异常是在 throw
语句而不是第16行上引发的.
Based on this question (What benefit does the new Exception filter
feature provide?).
The statement:
after doing some testing, I did not see the difference between both, the old and the new, I still see the exception from the place it was rethrown. So, or the information is not confirmed, I don't understand the Exception filters( that is why I am asking), or I am doing it wrong. Can you explaing me why this action filter are an advantage?
class specialException : Exception
{
public DateTime sentDateTime { get; } = DateTime.Now;
public int code { get; } = 0;
public string emailsToAlert { get; } = "[email protected]";
}
then:
try
{
throw new specialException(); //line 16
throw new Exception("Weird exception");
//int a = Int32.Parse("fail");
}
catch (specialException e) when(e.code == 0)
{
WriteLine("E.code 0");
throw; // <-Line 23
}
catch (FormatException e)
{
WriteLine("cond1 " + e.GetBaseException().Message+" "+e.StackTrace);
throw;
}
catch (Exception e) //when (cond2)
{
Console.WriteLine("cond2! " + e.Message);
throw;
}
Result:
The advantages of exception filtering are more to do with when the filter doesn't match, not when it does match. If you remove all of the catch
blocks except for the first one, and change the filter on the first catch
block to when(e.code != 0)
, then the callstack of the exception would indicate it was thrown on line 16.
The old way of implementing this would be as follows:
try
{
throw new specialException(); //line 16
throw new Exception("Weird exception");
//int a = Int32.Parse("fail");
}
catch (specialException e)
{
if(e.code != 0)
{
WriteLine("E.code isn't 0");
return;
}
throw;
}
In this case, the call stack will indicate that the exception was thrown at the throw
statement, rather than on line 16.
这篇关于为什么异常过滤器比捕获和重新抛出更可取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!