我想创建一个方法,通过我给该方法的参数抛出特定的异常。我有 3 个用户定义的异常,因此我不想每次使用它们时都抛出它们,而是想创建一个处理它的方法,所以我用我的方法给出的参数就是我想要抛出的异常,但是我该怎么做去做?
我想做这样的事情,但我不太确定该怎么做。
private void ExceptionMethod(custom exception)
{
try
{
//code that might fail
}
catch(exception ex)
{
throw new exception given by parameter(parameters from the exception);
}
}
Run Code Online (Sandbox Code Playgroud)
FWIW 我认为这不是一个特别好的主意。实际上,只要在发生异常的地方抛出异常,代码的未来维护者就会感谢你。(或者至少不会诅咒你)
如果您必须执行此操作,那么最好传递一个可以打开的枚举而不是异常本身,然后只需编写一个 case 语句来抛出您想要的异常。
除了这听起来像是一个坏主意之外,您还可以尝试以下操作:
private void TryElseThrow<TCustomException>(Action codeThatMightFail)
where TCustomException : Exception
{
try
{
codeThatMightFail();
}
catch (Exception e)
{
// Since there isn't a generic type constraint for a constructor
// that expects a specific parameter, we'll have to risk it :-)
throw
(TCustomException)Activator
.CreateInstance(typeof(TCustomException), e);
}
}
Run Code Online (Sandbox Code Playgroud)
像这样使用:
TryElseThrow<MyCustomException>(
() =>
{
throw new InvalidOperationException();
}
);
Run Code Online (Sandbox Code Playgroud)