In C#, younger developers use often "throw ex" instead of "throw" to throw exception to parent method.
Example :
try
{
// do stuff that can fail
}
catch (Exception ex)
{
// do stuff
throw ex;
}
"throw ex" is a bad practise because the stack trace is truncated below the method that failed. So it's more difficult to debug code. So the code must be :
try
{
// do stuff that can fail
}
catch (Exception ex)
{
// do stuff
throw;
}
My question is why compilator authorize this (or doesn't display a warning message ?) Is there a case which "throw ex" is useful ?
The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.
The letter “C” is arguably one of a few unnecessary letters. It makes the same sounds as the letters “K” and “S.” As it doesn't make a unique sound, why do we have it in our alphabet?
Is there a case which "throw ex" is useful ?
Sure - sometimes you want to truncate the stack trace - to avoid exposing implementation details, etc. Other times you may want to throw a new exception, which would mean the compiler would have to distinguish from just re-throwing the caught exception and throwing a new exception.
So why would you want the compiler to prevent you form doing something that 1) is not illegal and 2) could be useful?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With