Page 184 - CSharp/C#
P. 184
on line 6 because line 6 does not execute.
Logging as a side effect
Method calls in the condition can cause side effects, so exception filters can be used to run code
on exceptions without catching them. A common example that takes advantage of this is a Log
method that always returns false. This allows tracing log information while debugging without the
need to re-throw the exception.
Be aware that while this seems to be a comfortable way of logging, it can be risky,
especially if 3rd party logging assemblies are used. These might throw exceptions
while logging in non-obvious situations that may not be detected easily (see Risky
when(...) clause above).
try
{
DoSomethingThatMightFail(s);
}
catch (Exception ex) when (Log(ex, "An error occurred"))
{
// This catch block will never be reached
}
// ...
static bool Log(Exception ex, string message, params object[] args)
{
Debug.Print(message, args);
return false;
}
View Demo
The common approach in previous versions of C# was to log and re-throw the exception.
6.0
try
{
DoSomethingThatMightFail(s);
}
catch (Exception ex)
{
Log(ex, "An error occurred");
throw;
}
// ...
static void Log(Exception ex, string message, params object[] args)
{
Debug.Print(message, args);
}
https://riptutorial.com/ 130

