简体   繁体   English

我可以从try-catch的catch块中删除e吗?

[英]Can I delete the e from catch block of try-catch?

catch (HttpAntiForgeryException e)
{
    throw new HttpAntiForgeryException("Forgery Exception");
}

When I build the project, there is a warning said: The variable 'e' is declared but never used. 当我构建项目时,有一条警告说:声明了变量'e',但从未使用过。 Is that because the e is not necessary? 那是因为e不必要吗?

Yes. 是。 You can just simply write 你可以简单地写

catch (HttpAntiForgeryException)
{
    throw new HttpAntiForgeryException("Forgery Exception");
}

But, you are rethrowing same type of exception. 但是,您要抛出相同类型的异常。 You can also simply delete this catch block. 您也可以简单地删除此catch块。

It is no necessary if you don't want to do anything with the exception, in your case you are throwing custom message so its fine to use like this : 如果您不想执行任何例外处理,则没有必要,在这种情况下,您将抛出自定义消息,因此可以像这样使用它:

catch 
{
   throw new HttpAntiForgeryException("Forgery Exception");
}

or like this : 或像这样:

// For specific exception
catch (HttpAntiForgeryException)
{
       throw new HttpAntiForgeryException("Forgery Exception");
}

But you will not get any information regarding this exception, like error message, stack-Trace, inner exception etc.. I prefer you to handle the exception in Catch, Or properly log them for developer's reference 但是您不会获得有关此异常的任何信息,例如错误消息,堆栈跟踪,内部异常等。我更希望您在Catch中处理该异常,或者适当地记录它们以供开发人员参考

It's because You have not used the Variable e within any where of the catch block. 这是因为您没有在catch块的任何位置使用变量e。 You can easily catch that exception so you will get better understanding of the root cause of your exception than throwing a new exception. 您可以轻松捕获该异常,因此与引发新异常相比,您将更好地了解异常的根本原因。

catch (HttpAntiForgeryException e)
{
    Console.WriteLine(e.Message); // Console.Writeline or whichever way you want      
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM