-3

Why would I ever throw exceptions in code? (except for one specific scenario where I am developing a class library which the consumers of it, will not want / be able to change).

To be more specific, is there any reason to do this:

class EmailSender
{
   public void SendEmail(string recipient, string subject, string content)
   {
       if (string.IsNullOrEmpty(recipient))
       {
           throw new ArgumentNullException("exception text...");
       }

       // Send the email
   }

}

Instead of this:

class EmailSender
{
   public bool SendEmail(string recipient, string subject, string content)
   {
       bool result = false;

       try
       {
           if (string.IsNullOrEmpty(recipient))
           {
              logger.Error("Error text...");
           }
           else
           {
              // Send the email
              result = true;
           }
       }
       catch (Exception ex)
       {
           logger.Error(ex);
       }

       return result;
   }
}

Take into account that this class is in-house code and not something I am going to ship as a DLL or an open source project.

16
  • This is not a duplicate because my question here is not whether or not I should REDUCE the use of exception throw. I am asking why would I EVER use exception throw... Please remove duplicate suggestion. Dec 1, 2015 at 17:30
  • 1
    see also: Exceptions: Why throw early? Why catch late?
    – gnat
    Dec 1, 2015 at 17:34
  • 1
    Anyway, I have a good reason. If you swallow all of your exceptions in a logger, the only way you're ever going to know something bad happened is to examine the log. Dec 1, 2015 at 17:49
  • 5
    Perhaps. But a true or false doesn't tell you anything, except that the method succeeded or failed. An exception gives you an error message, a stack trace, and line numbers to the code that failed. Dec 1, 2015 at 17:56
  • 2
    Please stop adding meta commentary to your question! If you want to do that, you can put it here, in the comments. Dec 1, 2015 at 19:44

2 Answers 2

6

Are you asking why not always handle the error inside the same method the error is detected?

It is rarely the case that you can handle an error at the same level as where the problem is detected, it is only possible because you example is contrived. For example, what if the "send the mail" logic contains multiple method calls:

VerifyAdresses(recipient);
ConnectToSmtpServer();
PostMessage();

What if an error is detected in VerifyAdresses or ConnectToSmtpServer? If the method just logs the error and continues happily (as in your example), the PostMessage will be execute in any case, probably with a much more severe error as result.

You need to handle errors at the level where it is possible to gracefully recover. For example you can handle error in the mailing logic by not sending the mail. But you cannot gracefully handle an error locally inside VerifyAdresses() if that error prevents the whole operation of sending an mail. You need to be able to drop back up the call stack (possibly multiple steps) to the level where the error can sensibly be handled.


Edit: OK, you are really asking why not use C-style success/error result codes instead of exceptions. This discussion have been beaten to death, but suffice to say that the framework have made the choice for you. Result codes consistently used may in theory be as good as exceptions (if much more tedious and error prone), but since the framework already uses exceptions, it would be incredibly confusing and a waste of resources to use both exceptions and result codes in the same code base.

10
  • Not always, only in public functions. In your example, you are basically trusting on VerifyAccess to assert your code. This is GOTO programming style... Why not go with the same pattern and do this instead: If (VerifyAccess() && ConnectToSMTPServer()) { PostMessage(); } ? Dec 1, 2015 at 18:40
  • @UriAbramson: Bacause VerifyAccess() or ConnectToSMTPServer() might in turn call other functions, and an error could be detected multiple levels down.
    – JacquesB
    Dec 1, 2015 at 18:45
  • Well, going by the same pattern again, they would only call public functions which return a result object themselves so it would still work. This way you will have a SINGLE POINT OF ENTRY + EXIT throughout your entire code base and will not have to deal with exception GOTO unexpected logic. Dec 1, 2015 at 18:47
  • 3
    So are you are really asking why not use result codes (C style) to indicate errors, rather then exception?
    – JacquesB
    Dec 1, 2015 at 18:48
  • 1
    @UriAbramson: The discussion of exceptions versus result codes have been done many times already - see the sidebar. If you have a more specific question, you should update and clarify your question.
    – JacquesB
    Dec 2, 2015 at 7:31
0

Software generally consists of layers of functionality. (i.e. the application layer, the persistence layer, the network layer, the database layer, etc.)

A "library" is a layer of functionality which has been distanced from your code by having been moved into a separate binary file, but this is just a technicality, the point is that it is just another layer of functionality.

A layer of functionality generally communicates errors to the layer above by throwing exceptions.

So, if all of the software that you are writing lives in a single layer as thin as a crispy pizza dough, then yes, I suppose there may be no need for you to ever throw an exception.

But if you ever do anything non-trivial in your career, then you will of course work simultaneously at different layers, and therefore you will have a need to throw an exception in one layer, to be caught (or not) by a layer above.

4
  • Thanks for the answer... by saying "A layer of functionality generally communicates errors to the layer above by throwing exceptions." you are just making a statement without explaining why - which was my question exactly. And another thing - difference between Library and In-House code is that you cannot change a library because the code is inaccessible so in that case, you have to wrap and throw the exceptions in order to make them loggable (at the least) for calling code. Dec 1, 2015 at 19:00
  • you are just making a statement without explaining why - which was my question exactly. Oh, it did not occur to me that we were going to debate the usefulness of exceptions all over again. In this case, this question was rightfully closed as a duplicate. I thought you were asking something more subtle, like why throw exceptions in application code.
    – Mike Nakis
    Dec 2, 2015 at 0:55
  • What I mean is that you have other ways of comminicating through layers. Dec 2, 2015 at 6:23
  • But... I thought that we are not talking about communication in general, we are talking about communicating the occurrence of errors.
    – Mike Nakis
    Dec 2, 2015 at 10:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.