Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

10
  • 7
    Good answer. I would just emphasize the alternative much more. Commented Mar 4, 2020 at 16:37
  • 37
    Well, I don't think you should have a different exception class for every single throw statement, but I think you should have a different exception class for every discernible error case. That is, insufficient balance, and invalid status are different errors, and should have different error classes (could share a common parent exception). But if you can determine insufficient balance at multiple different locations in the code, they shouldn't be different exception classes just because they're thrown at a different time. That's what stack traces in logs are for. Commented Mar 4, 2020 at 16:45
  • 1
    Now that C# has finally added exception filters, I would think that instead of having many kinds of exceptions, it would be better to have one custom exception class with a function that would accept arguments related to the situations a handler would be interested in, and indicate whether the handler should catch the exception. Commented Mar 4, 2020 at 21:15
  • 2
    @Cruncher On the one hand I totally agree, on the other defining exceptions is sooo much hassle. New file, class and you need to update catchers etc. I often give in and throw something generic because adding an exception annoys me. I feel like there should an easier way to extend that. Commented Mar 5, 2020 at 6:55
  • 1
    @ChristianSauer I sympathize with this, I do. I do think that languages should have an easier way of targeting the catch for a thrown exception, like maybe being able to name the exception when you throw it, rather than having to predefine it. I can't count the number of times I've written raise Exception('Some Message') #TODO: Create exception class. But that doesn't mean we shouldn't be doing it. If I could write raise Exception(name='InsufficientBalanceError', message='...') it would be nice. Actually... I think I can probably build this in python. Commented Mar 5, 2020 at 15:26