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. C#
  4. Exceptions

Exceptions

Scheduled Pinned Locked Moved C#
questionhelp
11 Posts 5 Posters 0 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.
  • C CodingYoshi

    Lets say I have a hypothetical class which does something and upon error throws exception as below: public class Do { void DoSomething() { // do a few things // do a few more things if (SomethingWrong()) throw // some exception here } } I understand I have the option to either create my own custom exception, throw the exception, or simply create a new Exception object and add my own message to it and link the inner exception to it. My question is which of the above option is more ideal? Or should I throw ApplicationException? Also in client code, which of the following is a better programming habit: try { SomethingWhichCanThrowExceptionA(); SomethingWhichCanThrowExcepitonB(); // Some code here which does things and will not throw exception } Catch(ExceptionA) { // Recover } Catch(ExceptionB) { // Recover } Or: try { SomethingWhichCanThrowExceptionA(); SomethingWhichCanThrowExceptionAPassed = true; } Catch(ExceptionA) { // Recover } if (SomethingWhichCanThrowExceptionAPassed) { try { SomethingWhichCanThrowExcepitonB(); SomethingWhichCanThrowExceptionBPassed = true; } } Catch(ExceptionB) { // Recover } if (SomethingWhichCanThrowExceptionAPassed && SomethingWhichCanThrowExceptionBPassed) { // Some code here which does things and will not throw exception } Please shed some light on this or provide your own suggestions and how you do things.

    L Offline
    L Offline
    Luc Pattyn
    wrote on last edited by
    #2

    Hi, IMO and unless a pre-existing Exception type fits the bill accurately (as in NullReferenceException), you should create your own Exception type, give it an appropriate name ending on "Exception" and derive it directly or indirectly from Exception or better yet ApplicationException; even do consider a hierarchy of Exceptions. The advantage is you (and the users of your class) can then catch your new exception type(s) without catching more global Exceptions. :)

    Luc Pattyn [Forum Guidelines] [My Articles]


    Love, happiness and fewer bugs for 2009!


    C 1 Reply Last reply
    0
    • L Luc Pattyn

      Hi, IMO and unless a pre-existing Exception type fits the bill accurately (as in NullReferenceException), you should create your own Exception type, give it an appropriate name ending on "Exception" and derive it directly or indirectly from Exception or better yet ApplicationException; even do consider a hierarchy of Exceptions. The advantage is you (and the users of your class) can then catch your new exception type(s) without catching more global Exceptions. :)

      Luc Pattyn [Forum Guidelines] [My Articles]


      Love, happiness and fewer bugs for 2009!


      C Offline
      C Offline
      CodingYoshi
      wrote on last edited by
      #3

      But if all I am doing is simply reporting a message with a more friendly message, does it make sense to create custom exceptions? For example, RetrieveStudent(string id) { // Do a few things if (Error) throw new Exception("Failed to retrieve the student with id " + id); } And what about the 2nd question I had?

      L J C 3 Replies Last reply
      0
      • C CodingYoshi

        But if all I am doing is simply reporting a message with a more friendly message, does it make sense to create custom exceptions? For example, RetrieveStudent(string id) { // Do a few things if (Error) throw new Exception("Failed to retrieve the student with id " + id); } And what about the 2nd question I had?

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #4

        CodingYoshi wrote:

        simply reporting a message with a more friendly message

        even then, it is good practice; it is up to you to decide whether you value the precise catching it allows.

        CodingYoshi wrote:

        2nd question

        the latter: separate try-catch constructs offer better isolation, better readability. in the former, if you want B to happen even when A fails, your recovery code in the catch block would have to duplicate some code from the try block, which is bad. ultimately you could consider putting each of the try-catches in a separate method. :)

        Luc Pattyn [Forum Guidelines] [My Articles]


        Love, happiness and fewer bugs for 2009!


        1 Reply Last reply
        0
        • C CodingYoshi

          But if all I am doing is simply reporting a message with a more friendly message, does it make sense to create custom exceptions? For example, RetrieveStudent(string id) { // Do a few things if (Error) throw new Exception("Failed to retrieve the student with id " + id); } And what about the 2nd question I had?

          J Offline
          J Offline
          Jason C Bourne
          wrote on last edited by
          #5

          Exception handling is by definition about HANDLING an exception. When you want to display a friendly message, you are not handling anything. Handling an exception is for example retrying a connection to a remote machine after a timeout exception. This is real exception handling. Another form of exception handling is finding an alternative in case of disk I/O problem... writing on another disk or requesting the user to free some space for example. Any other thing that you might want to do, like logging or displaying a message, should be placed at one single location within your application, potentially the application controller. This "application host" component (it can be your Program.cs as well...) is supposed to do something (log, display a popup, exit the application or close the form, or whatever you think may be appropriate). But it can terminate as well, it is up to you to decide when your application is stable, and when it is not. Exception handling means what it says, you handle an exception when you can do something with it, otherwise you leave it going up the stack till it reaches the entry point. JC

          Jean-Christophe Grégoire

          C 1 Reply Last reply
          0
          • C CodingYoshi

            Lets say I have a hypothetical class which does something and upon error throws exception as below: public class Do { void DoSomething() { // do a few things // do a few more things if (SomethingWrong()) throw // some exception here } } I understand I have the option to either create my own custom exception, throw the exception, or simply create a new Exception object and add my own message to it and link the inner exception to it. My question is which of the above option is more ideal? Or should I throw ApplicationException? Also in client code, which of the following is a better programming habit: try { SomethingWhichCanThrowExceptionA(); SomethingWhichCanThrowExcepitonB(); // Some code here which does things and will not throw exception } Catch(ExceptionA) { // Recover } Catch(ExceptionB) { // Recover } Or: try { SomethingWhichCanThrowExceptionA(); SomethingWhichCanThrowExceptionAPassed = true; } Catch(ExceptionA) { // Recover } if (SomethingWhichCanThrowExceptionAPassed) { try { SomethingWhichCanThrowExcepitonB(); SomethingWhichCanThrowExceptionBPassed = true; } } Catch(ExceptionB) { // Recover } if (SomethingWhichCanThrowExceptionAPassed && SomethingWhichCanThrowExceptionBPassed) { // Some code here which does things and will not throw exception } Please shed some light on this or provide your own suggestions and how you do things.

            C Offline
            C Offline
            Colin Angus Mackay
            wrote on last edited by
            #6

            CodingYoshi wrote:

            create my own custom exception

            Yes.

            CodingYoshi wrote:

            simply create a new Exception object

            Never create an Exception object. Only something derived from Exception.

            CodingYoshi wrote:

            create a new Exception object and add my own message to it and link the inner exception to it.

            Where is this other Exception object coming from that you are putting in the inner exception? it isn't in the code you showed. Basically, create a custom exception class or use an existing specific exception if one exists. For example, I'll often create a DalException, or an excption for a specific part of the model in my application, e.g. a SalesException or BookingException. I won't create one for absolutely every exentuality, but I use them in logical groupings.

            CodingYoshi wrote:

            Or should I throw ApplicationException?

            I'm not a fan of the ApplicationException, it is too generic. You can derive from it if you want. In terms of how much code to put in your try block, that depends on the individual situation. If the two exceptions are distinct, as in your example, then I don't really see a problem with the first way you showed it. (i.e one try block.) I would suggest that if the two method calls can potentially produce the same kind of exception and you need to differenciate which method call produced the exception then your second example would be best.

            * Developer Day Scotland 2 - Free community conference * The Blog of Colin Angus Mackay


            Vogon Building and Loan advise that your planet is at risk if you do not keep up repayments on any mortgage secured upon it. Please remember that the force of gravity can go up as well as down.

            1 Reply Last reply
            0
            • C CodingYoshi

              Lets say I have a hypothetical class which does something and upon error throws exception as below: public class Do { void DoSomething() { // do a few things // do a few more things if (SomethingWrong()) throw // some exception here } } I understand I have the option to either create my own custom exception, throw the exception, or simply create a new Exception object and add my own message to it and link the inner exception to it. My question is which of the above option is more ideal? Or should I throw ApplicationException? Also in client code, which of the following is a better programming habit: try { SomethingWhichCanThrowExceptionA(); SomethingWhichCanThrowExcepitonB(); // Some code here which does things and will not throw exception } Catch(ExceptionA) { // Recover } Catch(ExceptionB) { // Recover } Or: try { SomethingWhichCanThrowExceptionA(); SomethingWhichCanThrowExceptionAPassed = true; } Catch(ExceptionA) { // Recover } if (SomethingWhichCanThrowExceptionAPassed) { try { SomethingWhichCanThrowExcepitonB(); SomethingWhichCanThrowExceptionBPassed = true; } } Catch(ExceptionB) { // Recover } if (SomethingWhichCanThrowExceptionAPassed && SomethingWhichCanThrowExceptionBPassed) { // Some code here which does things and will not throw exception } Please shed some light on this or provide your own suggestions and how you do things.

              H Offline
              H Offline
              HosamAly
              wrote on last edited by
              #7

              In answer to your second question, I'd suggest using the first style, which is more concise and clearer for readers. It clearly says "DoA(), DoB if A is successful, catch and handle A errors, catch and handle B errors". It's certainly cleaner IMO.

              My LinkedIn Profile

              1 Reply Last reply
              0
              • C CodingYoshi

                But if all I am doing is simply reporting a message with a more friendly message, does it make sense to create custom exceptions? For example, RetrieveStudent(string id) { // Do a few things if (Error) throw new Exception("Failed to retrieve the student with id " + id); } And what about the 2nd question I had?

                C Offline
                C Offline
                Colin Angus Mackay
                wrote on last edited by
                #8

                CodingYoshi wrote:

                But if all I am doing is simply reporting a message with a more friendly message, does it make sense to create custom exceptions?

                Yes, create the custom exception class. And I would suggest that instead of "a more friendly message" you provide a message that gives more context, that is more useful to the debugger, or the person reading the log file. It is very poor practice to be outputting exception messages to the user - There lies the potential for security breaches.

                * Developer Day Scotland 2 - Free community conference * The Blog of Colin Angus Mackay


                Vogon Building and Loan advise that your planet is at risk if you do not keep up repayments on any mortgage secured upon it. Please remember that the force of gravity can go up as well as down.

                1 Reply Last reply
                0
                • J Jason C Bourne

                  Exception handling is by definition about HANDLING an exception. When you want to display a friendly message, you are not handling anything. Handling an exception is for example retrying a connection to a remote machine after a timeout exception. This is real exception handling. Another form of exception handling is finding an alternative in case of disk I/O problem... writing on another disk or requesting the user to free some space for example. Any other thing that you might want to do, like logging or displaying a message, should be placed at one single location within your application, potentially the application controller. This "application host" component (it can be your Program.cs as well...) is supposed to do something (log, display a popup, exit the application or close the form, or whatever you think may be appropriate). But it can terminate as well, it is up to you to decide when your application is stable, and when it is not. Exception handling means what it says, you handle an exception when you can do something with it, otherwise you leave it going up the stack till it reaches the entry point. JC

                  Jean-Christophe Grégoire

                  C Offline
                  C Offline
                  CodingYoshi
                  wrote on last edited by
                  #9

                  I understand the point is to handle the exception by retrying, trying an alternative etc. but I am talking about times when you can not recover from it and you throw it to the caller and hopefully the caller can fix the problem.

                  C J 2 Replies Last reply
                  0
                  • C CodingYoshi

                    I understand the point is to handle the exception by retrying, trying an alternative etc. but I am talking about times when you can not recover from it and you throw it to the caller and hopefully the caller can fix the problem.

                    C Offline
                    C Offline
                    Colin Angus Mackay
                    wrote on last edited by
                    #10

                    If you cannot handle the exception or add anything meaningful to it then don't catch it.

                    * Developer Day Scotland 2 - Free community conference * The Blog of Colin Angus Mackay


                    Vogon Building and Loan advise that your planet is at risk if you do not keep up repayments on any mortgage secured upon it. Please remember that the force of gravity can go up as well as down.

                    1 Reply Last reply
                    0
                    • C CodingYoshi

                      I understand the point is to handle the exception by retrying, trying an alternative etc. but I am talking about times when you can not recover from it and you throw it to the caller and hopefully the caller can fix the problem.

                      J Offline
                      J Offline
                      Jason C Bourne
                      wrote on last edited by
                      #11

                      Exceptions generally match with their namespace and are thrown via their public members (although, a property should never throw an exception). You are not really supposed to make plenty of exceptions for the tons of different possible problems. Exception handling is really about exception handling. A public method in System.IO.File.Read() could for example throw a System.IOException , without more. Internally, you don't have to handle that at many levels, you just leave it going up till the public method that was called. In this public method, you may indeed have a problem because another component lower in the chain had a problem, for example a network problem during the Read operation. Well, yes, then you receive a System.NetworkException for example, you catch it and rethrow a new exception of type System.IOException with the original exception provided as "inner exception". This is the normal way of doing. So, imagine that you create a new library ComicSoft.ZipUtilities , in the simplest case possible, you can think of one single custom exception for the whole assembly called ComicSoft.ZipUtilities.ZipUtilityException which could be thrown by any public method. And when you have to throw your custom exception because something else crashed, you just give the original exception as parameter when you instantiate it. This is really the simple and academic case, exception handling and rethrow policies is a huge debat ;-) Exception handling can be made much more elaborate, and exceptions should ideally be forseen to be technically useful. Forsee codes, categorize exceptions, find ways to help locating the problems etc... But in its simplest form, what you should do is one or more exception for public methods, depending on the different possible feedbacks that you think will need to provide. If you start doing that internally, then it really should be to use the exception type as condition to execute real handling.

                      Jean-Christophe Grégoire

                      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