Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. .NET (Core and Framework)
  4. When to Define a Custom Exception

When to Define a Custom Exception

Scheduled Pinned Locked Moved .NET (Core and Framework)
csharptutorialquestiondiscussion
31 Posts 19 Posters 6 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Patrick Skelton

    Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

    R Offline
    R Offline
    realJSOP
    wrote on last edited by
    #8

    I try to handle an exception-causing code to avoid throwing an exception, and let the code fail gracefully (not necessarily terminating a process or action, but using reasonable properties to allow it to continue.

    ".45 ACP - because shooting twice is just silly" - JSOP, 2010
    -----
    You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
    -----
    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

    1 Reply Last reply
    0
    • P Patrick Skelton

      Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

      P Offline
      P Offline
      PIEBALDconsult
      wrote on last edited by
      #9

      Yeah, it depends on the situation. I use the built-in Exceptions when they seem appropriate and define my own when I want to add more information. As with Exceptions raised by ADO.net code -- I can throw problem-specific Exceptions (duplicate, referential integrity, etc.) that also include the text of the statement and any parameters involved so they can be handled appropriately by the application. Also, if you do define your own Exception, derive it from the appropriate base Exception -- your own OutOfRange should derive from the base OutOfRange.

      1 Reply Last reply
      0
      • P Patrick Skelton

        Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

        N Offline
        N Offline
        Not Active
        wrote on last edited by
        #10

        I'll agreed with the other recommendations also. First, try to prevent the exception in the first place but we all know that is not possible or desirable in some situation. If the exception fits a built-in type, ArgumentNullException for instance then by all means use it. However, if you need to differentiate or have a custom case then certainly creating your own is valid.


        I know the language. I've read a book. - _Madmatt

        R 1 Reply Last reply
        0
        • N Not Active

          I'll agreed with the other recommendations also. First, try to prevent the exception in the first place but we all know that is not possible or desirable in some situation. If the exception fits a built-in type, ArgumentNullException for instance then by all means use it. However, if you need to differentiate or have a custom case then certainly creating your own is valid.


          I know the language. I've read a book. - _Madmatt

          R Offline
          R Offline
          realJSOP
          wrote on last edited by
          #11

          I generally just do this instead of creating custom exception objects:

          catch (Exception ex)
          {
          throw new Exception("My custom exception message", ex);
          }

          ".45 ACP - because shooting twice is just silly" - JSOP, 2010
          -----
          You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
          -----
          "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

          N L D 3 Replies Last reply
          0
          • R realJSOP

            I generally just do this instead of creating custom exception objects:

            catch (Exception ex)
            {
            throw new Exception("My custom exception message", ex);
            }

            ".45 ACP - because shooting twice is just silly" - JSOP, 2010
            -----
            You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
            -----
            "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

            N Offline
            N Offline
            Not Active
            wrote on last edited by
            #12

            Yes but there are times when it is advantageousness to differentiate between a custom exception

            try
            {
            Foo();
            }
            catch(UserIsMoronException ex)
            {
            BeatSensless();
            }
            catch(Exception ex)
            {
            Log();
            }


            I know the language. I've read a book. - _Madmatt

            R 1 Reply Last reply
            0
            • D Daniel Turini

              I like to create my own exceptions, except (no pun intended) for the most basic validations, because the situation you mentioned is a bit rare in business applications. The custom exception often adds semantic information. In a similar situation, NegativeDepositAmmountException IMHO could be much more meaningful than ArgumentOutOfRangeException. If your number has a strict domain, often is a class or some entity that needs special treatment. Another similar case is where you can't receive a Customer with an empty or null Customer.Address field. What would you prefer to receive? A NullReferenceException or a EmptyAdressException? It means a lot more manual work, but in the long run it pays when you deploy your code to your customers.

              I see dead pixels Yes, even I am blogging now!

              D Offline
              D Offline
              Dan Neely
              wrote on last edited by
              #13

              If you have NegativeDepositAmmountException inherit ArgumentOutOfRangeException you can have the best of both worlds. You can encode as much semantic information as you need, while simultaneously making it easy for a consumer to handle common error cases without having to learn all the details of your implementation up front.

              3x12=36 2x12=24 1x12=12 0x12=18

              D 1 Reply Last reply
              0
              • P Patrick Skelton

                Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

                S Offline
                S Offline
                Single Step Debugger
                wrote on last edited by
                #14

                The well designed application doesn’t needs exceptions! :-D In a more serious note, the only case I create custom exceptions is when I’m dealing with COM objects and/or native libraries in order to wrap their error handling and error messages. In any other cases the build-in exceptions and re-throwing them in some cases seems to be enough for me.

                There is only one Ashley Judd and Salma Hayek is her prophet! Advertise here – minimum three posts per day are guaranteed.

                1 Reply Last reply
                0
                • N Not Active

                  Yes but there are times when it is advantageousness to differentiate between a custom exception

                  try
                  {
                  Foo();
                  }
                  catch(UserIsMoronException ex)
                  {
                  BeatSensless();
                  }
                  catch(Exception ex)
                  {
                  Log();
                  }


                  I know the language. I've read a book. - _Madmatt

                  R Offline
                  R Offline
                  realJSOP
                  wrote on last edited by
                  #15

                  Mark Nischalke wrote:

                  catch(UserIsMoronException ex)

                  They REALLY need to add this one to the framework. :)

                  ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                  -----
                  You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                  -----
                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

                  Y 1 Reply Last reply
                  0
                  • R realJSOP

                    Mark Nischalke wrote:

                    catch(UserIsMoronException ex)

                    They REALLY need to add this one to the framework. :)

                    ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                    -----
                    You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                    -----
                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

                    Y Offline
                    Y Offline
                    Yusuf
                    wrote on last edited by
                    #16

                    John Simmons / outlaw programmer wrote:

                    Mark Nischalke wrote: catch(UserIsMoronException ex) They REALLY need to add this one to the framework.

                    They did, and 85% of the exceptions where caught by, ... you guessed it right... ;P

                    Yusuf May I help you?

                    1 Reply Last reply
                    0
                    • P Patrick Skelton

                      Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

                      H Offline
                      H Offline
                      HimanshuJoshi
                      wrote on last edited by
                      #17

                      Depends on the situation. Mostly one should use built in exceptions, but for some reason the exception is too generic or does not fit in your scenario, then creating a custom exception is better.

                      1 Reply Last reply
                      0
                      • D Dan Neely

                        If you have NegativeDepositAmmountException inherit ArgumentOutOfRangeException you can have the best of both worlds. You can encode as much semantic information as you need, while simultaneously making it easy for a consumer to handle common error cases without having to learn all the details of your implementation up front.

                        3x12=36 2x12=24 1x12=12 0x12=18

                        D Offline
                        D Offline
                        Daniel Turini
                        wrote on last edited by
                        #18

                        It's a very nice idea, but not always practical, and could lead to some inconsistencies. I learned the hard way to take a lot of care when deriving a class, and follow more rigidly LSP (Liskov Substitution Principle). In the same example, EmptyAdressException cannot be derived from NullReferenceException, in the same way a Square cannot be derived from a Rectangle.

                        I see dead pixels Yes, even I am blogging now!

                        D L 2 Replies Last reply
                        0
                        • D Daniel Turini

                          It's a very nice idea, but not always practical, and could lead to some inconsistencies. I learned the hard way to take a lot of care when deriving a class, and follow more rigidly LSP (Liskov Substitution Principle). In the same example, EmptyAdressException cannot be derived from NullReferenceException, in the same way a Square cannot be derived from a Rectangle.

                          I see dead pixels Yes, even I am blogging now!

                          D Offline
                          D Offline
                          Dan Neely
                          wrote on last edited by
                          #19

                          I'm not following. If I understand LSP correctly it says that if I derive Square from Rectangle that Squares must have all the properties of a rectangle; which they do so the derivation should be allowed under LSP. What am I missing?

                          3x12=36 2x12=24 1x12=12 0x12=18

                          D 1 Reply Last reply
                          0
                          • D Dan Neely

                            I'm not following. If I understand LSP correctly it says that if I derive Square from Rectangle that Squares must have all the properties of a rectangle; which they do so the derivation should be allowed under LSP. What am I missing?

                            3x12=36 2x12=24 1x12=12 0x12=18

                            D Offline
                            D Offline
                            Daniel Turini
                            wrote on last edited by
                            #20

                            That's what I thought at first, too. But LSP is not about properties, nor methods. LSP is about "substitution", and that is more closely related to an specialization. A Red Rectangle can be derived from a Rectangle, but a Square is much more an abstract class on its own. The "is a" relationship of OO is flawed; you can read more about that on this pdf[^]

                            I see dead pixels Yes, even I am blogging now!

                            1 Reply Last reply
                            0
                            • P Patrick Skelton

                              Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

                              R Offline
                              R Offline
                              Ray Cassick
                              wrote on last edited by
                              #21

                              My decision is to define a custom exception when the need to do so is... well... exceptional :) Really though… If you have an exception definition that clearly fits an existing model then use it, why reinvent the wheel at all? If you are creating a new failure state, usually most likely based upon things like a domain specific business rule, then you define a new exception of your own design. BUT you have to keep in mind that quite often even doing this can cause issues because as we all know business rules change. This means that you may want to be slightly less specific and more generalized by defining a business rule exception and allowing it to express the rule broken, and the why it was considered broken enough to trigger the exception. I would like to know what books you say are specifically stating that new exceptions should always be defined instead of using the Dotnet ones. I would have to have a conversation with that author :) I am not even sure I see the value in writing all custom exceptions when creating a whole new code library of your new library is something that sits on top of the Dotnet framework. If you are writing something that is completely disconnected at all form the Dotnet stuff then yeah, you have to create your own exceptions to throw, but that makes no sense in this context really since your question was more related to being told to not use Dotnet exceptions :). If you did want to keep all the exceptions specific to your application layer then there is nothing from stopping you from writing all your own custom exception code, but I would still recommend that you consider catching the Dotnet specific stuff and then just re throwing your own as a general application side exception and then include the Dotnet exception in that object. Seems a bit messy but I guess it is doable and will not require too much writing on your part. Just remember that every additional line of code you have to write can possibly introduce a new error (and thus CAUSE an exception :) ) so I like to keep them down to a minimum. One other argument I would make for maintaining the existing exceptions provided by the framework is that anytime they change you need to ensure that your code changes also. This means that if you have wrapped all of the Dotnet exceptions in your code, any time the framework changes you have to review all those changes to see what effects they have on your code. Not that you may not have to do the same if the base libraries change their exceptions and you have to catch th

                              1 Reply Last reply
                              0
                              • P Patrick Skelton

                                Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

                                P Offline
                                P Offline
                                Patrick Fox
                                wrote on last edited by
                                #22

                                I think you would do this when you want to specify additional information beyond a string message describing what went wrong. Some exceptions take advantage of their name to provide additional information, like NullReferenceException. If one is thrown, clearly something is null and the code didn't expect it to be. SqlException contains additional properties related to line numbers in stored procedures that failed, for example. So, if you'd like to provide additional properties to describe what went wrong, create a class that inherits Exception that has those properties.

                                1 Reply Last reply
                                0
                                • R realJSOP

                                  I generally just do this instead of creating custom exception objects:

                                  catch (Exception ex)
                                  {
                                  throw new Exception("My custom exception message", ex);
                                  }

                                  ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                                  -----
                                  You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                                  -----
                                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

                                  L Offline
                                  L Offline
                                  Lost User
                                  wrote on last edited by
                                  #23

                                  Having a type-safe object has some advantages over a string. It's harder to filter if you're examining a string, and I like having a class that describes the problem and being able to catch and handle that specific case. Or worse- let the user decide whether or not those kind of exceptions need be logged (like file-access errors for the sysadmin, common networkexceptions for the networkadmin, and whether the user allows the app to send unhandled exceptions with a stacktrace back home) There's a string in the custom exception of course, along with placeholders for values to help diagnose the problem. But in code, I can act on the object itself, and I don't need to depend on the formatting of a string. It's a matter of preference, I guess, as you can accomplish the same visual and functional endresult. No, the worst kind of exceptions are translated ones. Yes, I know about the unlocalize website, but that's not exactly convenient. I'm hoping that I can rectify some by removing the .NET language packs from my PC.

                                  I are Troll :suss:

                                  1 Reply Last reply
                                  0
                                  • D Daniel Turini

                                    It's a very nice idea, but not always practical, and could lead to some inconsistencies. I learned the hard way to take a lot of care when deriving a class, and follow more rigidly LSP (Liskov Substitution Principle). In the same example, EmptyAdressException cannot be derived from NullReferenceException, in the same way a Square cannot be derived from a Rectangle.

                                    I see dead pixels Yes, even I am blogging now!

                                    L Offline
                                    L Offline
                                    Lost User
                                    wrote on last edited by
                                    #24

                                    Also, a inherited class should only throw exceptions that the base class throws, or descendants thereof.

                                    I are Troll :suss:

                                    1 Reply Last reply
                                    0
                                    • P Patrick Skelton

                                      Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

                                      R Offline
                                      R Offline
                                      RobCroll
                                      wrote on last edited by
                                      #25

                                      I'll typically only write custom exceptions in the Model (Business) layer. The reason for doing this is so the presentation layer can consume the exception and display a message which is non-technical and meaningful to the user. Probably breaches best practices but it works well example: Model receives an OutOfRangeException, Model creates a MyModelException with the message "The number of passengers must be greater than 0" and throws the exception to the presentation layer.

                                      Architecture is extensible, code is minimal.

                                      1 Reply Last reply
                                      0
                                      • P Patrick Skelton

                                        Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

                                        P Offline
                                        P Offline
                                        Patrick Skelton
                                        wrote on last edited by
                                        #26

                                        Wow! What a response. Thanks to everyone. Some very good advice in there, and lots to think about. I'm glad I asked; that was really helpful. Best wishes, Patrick

                                        P 1 Reply Last reply
                                        0
                                        • P Patrick Skelton

                                          Hi, I would like to get a few expert opinions on the question of when to define a custom exception. According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly. If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill. I would be very interested to hear other opinions on this subject or get links to good articles on this subject. Best wishes, Patrick

                                          D Offline
                                          D Offline
                                          dan sh
                                          wrote on last edited by
                                          #27

                                          Patrick Skelton wrote:

                                          According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use

                                          If that was the case, why the hell are those classes public? I have never read anything like that. You should be creating custom exceptions only when your code interacts with something external. For instance, a service should return custom exceptions back to client in order to hide the complete information of the actual exception. Not because you are ashamed of it but it doesn't makes sense client knowing details of services. Same logic I use in case anything wrong happens in database. Apart from my data layer code, none of the layers get the complete trace of the error. Apart from all the custom exceptions, I also keep one catch block taking in Exception as a type (in the outermost code layer) just in case we get an exception which I have not handled properly.

                                          "Your code will never work, Luc's always will.", Richard MacCutchan[^]

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups