Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the C# compiler authorize "throw ex" in catch, and is there a case where "throw ex" is useful?

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 ?

like image 630
binard Avatar asked Jul 10 '14 13:07

binard


People also ask

Why does the letter c exist?

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.

Is the letter C unnecessary?

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?


1 Answers

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?

like image 129
D Stanley Avatar answered Sep 22 '22 12:09

D Stanley