-
Notifications
You must be signed in to change notification settings - Fork 6k
Description
There are a lot of examples demonstrating the use of "catch(Exception)" or "catch{}" that leads application to unexpected behavior.
Literally such catch block says "whatever happened lets do one thing". In most cases it does not make sense.
For example, on this page there is code catch (Exception ex) { Console.WriteLine("Exception caught in CreateTestMessage1(): {0}", ex.ToString() );
In case of any issues with application itself or environment that finished by Exception (NullReferenceException, OutOfMemoryException etc) we just swallow that exception and put some information in to console. First of all any unhandled exception in console application will be written to console by itself. Second, should the caller of this method be notified about something happened? Again, in most cases yes, because mostly code that follows this method assumes this method success. If the task was just "try to send email" then we should put appropriate exception types (SmtpFailedRecipientException, SmtpException etc), because other exceptions do not mean email was not sent, situation when exception was thrown after email was sent possible too. In common other exceptions not stated in documentation can be not related to email sending at all.
Statement from c# Programming Guide:
Do not catch an exception unless you can handle it and leave the application in a known state. If you catch System.Exception, rethrow it using the throw keyword at the end of the catch block.
More information here: MSDN
I think in most cases try/catch blocks can be just removed from examples. Sometimes they can be replaced/improved by exact exception type catching and sometimes by rethrowing.
In very rare case catch{} makes sense in context of application lifetime considering.
We have fixed such several examples, but there are much more of them (example) (especially in code related to UWP).
I'd like to assign to it, but anyway I want to discuss it as new examples will be added, may be it makes sense to create documentation tests, for example.
@mairaw , asking you, please, kindly review this issue as you already had a deal with it