简体   繁体   中英

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. Is that because the e is not necessary?

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.

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

It's because You have not used the Variable e within any where of the catch block. 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      
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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