Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

I overuse try-catches in my programming

  1. Nov 10, 2015 #1
    My applications seriously look like

    Code (Text):

    public void ExecuteCommand ( )
    {
       // ...
        try
        {
             CompareLastTwo();
        }
        catch ( Exception e )
        {
            Console.WriteLine("Error: {0}", e.Message);
        }
       // ...
    }

    public void CompareLastTwo ( )
     {
          // ...
           try
           {
               // ...
               Something();
           }
          catch ( Exception )
          {
              throw;
          }
           // ...
        }

    public void Something ( )
    {
         try
         {
            // ...
         }
        catch ( Exception )
        {
            throw;
        }
    }
     
    It is the cancer that is killing my programs. How can beat this disease?
     
  2. jcsd
  3. Nov 10, 2015 #2
    And why does this forum have C/C++/C# as a category? C# isn't in the same category as the other two.
     
  4. Nov 10, 2015 #3

    Mark44

    Staff: Mentor

    The Insert menu (+ in the green menu bar) has a Code menu item. In the Code dialog, one of the choices is C/C++. There's not one for C# for the reason that the site owner, Greg Bernhardt, hasn't added C# as a choice.

    Edit: I thought you were talking about the code tags ([code=c] ... [/code] that go around your code. I didn't realize you were talking about the tags in the title bar.

    With regard to the plethora of try ...catch blocks in your code, some simple advice is to make the try blocks as small as possible, to focus on specific areas of code that could possibly throw an exception. Hopefully you do enough testing and incorporate sufficient logic before the code goes into production to eliminate many of the potential exceptions that could be thrown. If so, then your code only has to handle truly exceptional cases. Also, if a function or method that is some way down the call stack throws an exception, the catch block should rethrow it to allow it to bubble up to the next level in the call stack.
     
  5. Nov 10, 2015 #4
    I've been using exceptions in non-exceptional cases. The alternative to try-catching a function is to make it return some value that indicates success or failure, and some message along with that value. I guess I should be taking the word "exception" literally?
     
  6. Nov 10, 2015 #5
    Rather than deciding whether to use exceptions based only on the murky question of how exceptional the error is, I suggest also considering scope. Can you handle the error locally? Your code makes me wonder whether you are aware that exceptions propagate up the call stack. You need not handle them in the scope where they are thrown. This is indeed one of the strengths of exceptions.
     
  7. Nov 10, 2015 #6

    phinds

    User Avatar
    Gold Member
    2016 Award

    That's OK. I don't use them at all, so together we're at about the right mix. :smile:
     
  8. Nov 10, 2015 #7
    Put your catch at the highest level that it's usable. If you are inside of a function, and one of the commands within the function can throw an exception that invalidates the entire method, don't catch it there, let it propagate up.
     
  9. Nov 10, 2015 #8

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Java and C# can be rather trying languages (pun intended).

    That said, there's no point in using try-catch like this:
    Code (Java):
    public void outer_function ( )
    {
        try
        {
            inner_function ();
        }
        catch (Exception)
        {
            throw;
        }
        // More stuff
    }
    Just call inner_function() without the try-catch. A catch that only does a throw; has no purpose. Simply let the exception bubble up the call stack until you get to a point where it can be handled. What's not pointless in a catch block:
    • Somehow handling the exception.
    • Relabeling the exception so you don't have to have so many different kinds of exceptions. This is particularly useful in Java where you have to declare every single exception that might propagate out of a function. Yech!
    • Encapsulating the exception so as to give context. Letting a low level exception propagate all the way to the top doesn't help the user solve the problem. For example, suppose you are writing a reader for input files of a specific format. Suppose the input file at hand does not follow that format. The problem will usually be discovered by some low-level function that doesn't know the context of what it is processing. That function throws an exception that doesn't say much. While a mid-level function may not be able to handle the exception, it can add context in the form of a new exception that encapsulates the low level exception.
     
  10. Nov 19, 2015 #9
    No way ! There is a law for the use of Try Catch. Because a processing unit is perfectly deterministic, you are able to predict the different case of faillure and test it in the function. Try catch need to be used ONLY in INPUT OUTPUT opération that are not deterministic from the computer point of view. A summary, you need try catch for :

    Keyboard, mouse
    HDD access, file management
    DMA operation, network, socket ... etc.

    With this rule you will use try catch only at the right place.
     
  11. Nov 19, 2015 #10

    phinds

    User Avatar
    Gold Member
    2016 Award

    I think you misunderstand the purpose of try catch. Or, perhaps you always write utterly perfect programs with no mistakes that might cause an error message.
     
    Last edited: Nov 19, 2015
  12. Nov 19, 2015 #11
    Not true, you should consider nothing to be deterministic, that's why they have exceptions. Hell this might fail.

    Code (C):
    int * o = new int(5);
    You need to think of every possibility, not just those that should happen. The above should never fail, but it's possible that it will (out of memory error.)
     
  13. Nov 19, 2015 #12
    "I think you misunderstand the purpose of try catch. Or, perhaps you always write utterly perfect programs with no mistakes that might cause an error message."
    Sorry but you need to predict the bug because you need to put "throw". Where you put throw, you can just resolve the problem or return an error code.

    "int* o = new int(5);"
    Sorry but it's exactly an input output exception.... caused by the memory allocation.

    You must consider the CPU as deterministic because, if not, then throw and catch are not deterministic too so the catch process is useless.
     
  14. Nov 19, 2015 #13

    phinds

    User Avatar
    Gold Member
    2016 Award

    I say again, I think you misunderstand the purpose of try catch. Or, perhaps you always write utterly perfect programs with no mistakes that might cause an error message. The POINT of the try catch is to help ID problems that need fixing and it is a step up from just error messages because it allows for graceful degradation. Clearly I'm not going to change your mind on this, so you just go right on believing what you like.

    By the way, you keep pointing out the the computer is deterministic, which simply further verifies that you don't understand the purpose of try catch. OF COURSE the computer is deterministic. So what? That has nothing to do with good error handling.

    By the way, learn to use the quote button instead of cut/paste w/ quotes.
     
  15. Nov 19, 2015 #14

    Mark44

    Staff: Mentor

    No, running out of memory is NOT an IO exception.
     
  16. Nov 19, 2015 #15
    What? It's not possible to release software with no bugs in it anywhere. Even small software products can be tens of millions of lines of code, you can't put a try/catch around every single line of code that's got an unknown in it. The point of putting throws at the bottom and catching them at the top is so that you don't have to do tons and tons and tons of validation, not to mention spending every second of your day writing error handlers. Are you telling me that your code is always const correct? Volatile correct? Thread safe? Future proof? no throw declared? Branch prediction correct? Has ieee special flag handlers? Proper SIGTERM handling? How can I hire you?

    Exceptions have nothing to do with the CPU, the CPU being deterministic (which it's not) has nothing to do with proper code design.

    Not correct. Malloc will return NULL, but new will throw a std::bad_alloc exception. Or do you mean that it's not IO? I would agree with that, IO usually means talking to the keyboard, mouse, sockets, graphics card... not RAM.
     
  17. Nov 19, 2015 #16

    Mark44

    Staff: Mentor

    Yes, that's exactly what I mean.
     
  18. Nov 19, 2015 #17
    const correct? Volatile correct? Thread safe? Future proof? no throw declared? Branch prediction correct? Has ieee special flag handlers? Proper SIGTERM handling? How can I hire you? (Branch misprédiction...etc have nothing to do here)

    Ok well, i think that i need an example, because i realy don't understand where try catch save you WITHOUT explicitely throwing exception with a test.
    For example, thread safe. Imagine i made a program using two thread using the same resources, i put a mutex on the resources. So... now... what append ? it work. Now, i forget a mutex somewhere and the two thread use the same class. The class parameter become wrong. Now, how try catch save me without testing that the class is in a good state ? Give me a concrete example please.

    By the other hand, all this is just a programming tool, because once compiled, throw, catch, etc, are remplaced by jumps so, may be there is no rules because it's exactly the same thing as return -3;
     
  19. Nov 20, 2015 #18
    a C# example
    PHP:

    const int maxNum=1000;
    while(beginAgain<maxNum)
    try
    {
        lock(resourceObjectDataToBeLocked)
        {
            // Let your threads access this resource
        }
    }
    catch(ExceptionFromThreads)
    {
    }
    catch(ExceptionDueToDeadLocks)
    {
       // Change beginAgain value to make it work again till 1000
    }
    catch() // catch everything else
    {}
    }
     
    If your class happens to contain no ExceptionDueToDeadLocks but the program does throw one, then you've failed to recognize how important try-catch is.
    To me, try-catch is a safe logical combination of if-then-else and goto; It is a technique, not a concept; The larger the project the more try-catch I can see in all source code.
    Without it in one's code particularly while the code is trying to access 3rd party library's methods/functions, it is pretty safe for people to conclude that s/he actually doesn't have much experience working with different "real" large industrial applications. Try-catch use also induces performance hits to the whole program but we won't trade performance for quality and safety in this endless fight against potential bugs.
     
  20. Nov 22, 2015 #19

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    There's a whole lot more to exceptions than a mere goto. Suppose function a() calls function b(), which calls ... which calls function y(), which calls function z(), which throws some exception. Suppose that the catch block that handles this exception is inside function a().

    A lot of stuff has to be done along the way to reaching the block that will handle this exception. The system needs to unwind the call stack. Local variables declared along the way between functions a() and z() need to be destructed in C++ (in reverse order, that is z() first, a() last). In Java or C#, variables allocated along the way need to be marked as subject to garbage collection, resources need to be closed or disposes, and intervening finally statements need to be executed (again in reverse order).

    There are a lot of ways in which things can go wrong in this process. In C++, what happens if a destructor throws an exception? Now there are two exceptions that need to be dealt with, the original exception thrown in function z(), and the exception raised in that destructor. The C++ solution to this problem is to call the function std::terminate(). A similar problem occurs in C# and Java when a finally statement throws an exception. The solution by these languages is to discard the original exception and start processing the newly thrown exception. The solution to these problems is to never allow exceptions to propagate out of destructors in C++ or out of finally statements in C# and Java.
     
  21. Nov 22, 2015 #20

    harborsparrow

    User Avatar
    Gold Member

    My advice won't be popular, perhaps. Use try-catch pretty much comprehensively just like you are. It forces you to think about errors and how they should be handled.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: I overuse try-catches in my programming
  1. Try out my new program (Replies: 19)

Loading...