Thread: About try and catch performance.

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    64

    About try and catch performance.

    Is it true that Try... catch.. affects runtime performance? Most of my friends told me that it is slow and should not be use most of the time.

    I noticed this also when I'm using it but not always. What can you say? I googled it and found bunch of threads about it. Now, I'm asking here in the forum and wants to know if this is true in C++.

    Thank you
    Sarah22

  2. #2
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    The C++ exception mechanism was designed with "you don't pay for what you don't use" in mind.

    The C++ exception mechanism doesn't necessarily cost anything unless you `throw' an exception.

    That said, in practice most compilers implement exceptions through `setjmp'/`longjmp' or similar. This exception model has some overhead whether you use exceptions or not.

    Now that that is out of the way, I challenge you to do what exceptions do for C++ without any cost.

    And now, exceptions should be used exactly when they should be used and at no other times. You fail if you use anything other than exceptions when you need exceptions. You fail if you use exceptions as "return codes". You fail if you `catch' only to `throw;'. You can use exceptions wrong in a lot of ways. That doesn't make exceptions slow. It makes you a lousy programmer.

    Soma

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by phantomotap View Post
    The C++ exception mechanism was designed with "you don't pay for what you don't use" in mind.
    In terms of performance, yes. But exceptions can have a significant impact on code size. I've seen code shrink by more than half when exception tables were turned off. Obviously, you cannot do that in code that actually throws exceptions.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  4. #4
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Exceptions should not be used most of the time: they should only be used for exceptional cases. That is to say, when an exception happens, that should mean that there's something wrong, and therefore you don't care too much about performance anymore. So generally, exceptions are implemented such that throwing and catching an exception is indeed slow, but not throwing an exception is fast.

    But exceptions are a good mechanism for dealing with those exceptional errors. When some resource becomes unavailable for instance. It simplifies your logic, and separates out the special case handling from the normal code. This can be a speedup, because you don't need logic at intermediate levels do check if an exception occurred. You only need logic to throw the exception, and to catch it were something can be done to handle it.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  5. #5
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Lets not forget thought that there are some libraries that use exceptions. In which case you have no choice, but to use try/catch no matter how slow they are.

    There is also the clarity side of it. Writing
    Code:
    if (!Fun()) {
      cout << "Error" << endl;
      exit(0);
    }
    is not at all nice. The important information is "execute Fun() and if something wrong notify and exit.

    Imagine the above multiple times. It is just ugly. The try/catch syntax is much nicer and much clearer.

    Using other methods like
    Code:
    errorCode = Fun();
    errHandle(errorCode);
    will save you a lot of typing and making clearer. You can also write it as
    Code:
    errorCode = Fun(); errHandle(errorCode);
    and save a line. But again if you try to read the code you will read errorCode first, when you would prefer to read Fun() first, since that is the important information.

    An improvement might be using a global variable for all error codes and having one error function and just do
    Code:
    Fun();  err("Error");
    which would simulate the syntax from other languages
    Code:
    Fun() or die("Error");
    or just ignore me cause I am being irrelevant and contradicting myself...

  6. #6
    Registered User
    Join Date
    Mar 2010
    Posts
    68
    Let me sum up everything you need to know about try, catch and throw..... don't use them.

  7. #7
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    But exceptions can have a significant impact on code size.
    No. This, like speed, is an implementation issue.

    While the exception mechanism can increase code size, I don't believe you have any non-trivial example where they double the size of the binary.

    Soma

  8. #8
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Quote Originally Posted by smasherprog View Post
    Let me sum up everything you need to know about try, catch and throw..... don't use them.
    To clarify, we are talking about performance. If performance wasn't an issue, try/catch maybe the best way to write certain pieces of code.

    And keep in mind that in order to say something is slow or fast you have to compare it with something else. Because if you have
    Code:
    try {
       forever();
    } catch {};
    and forever() takes forever to execute, I don't think you would care of adding a small overhead which would require 0.0001% of the time of forever() to execute.

    Furthermore, clarity can offer a better chance for optimization. Thus, using try/catch might result in a better performance in the end.

    The only think you need to know is that the try/catch mechanism has a cost in performance...

  9. #9
    Registered User ~Kyo~'s Avatar
    Join Date
    Jun 2004
    Posts
    320
    Actually there are times when as previously stated do have a good use for try and catch(...) code blocks.

    I will refer to a class I posted here a while back it does use the try and catch(...) blocks it is even for a game now that being said I will explain why in this case at least it doesn't destroy performance. Generally when a dialogue is open there is nothing going on in the background - that being said try to print with given font if we can't use a default font so the program does not crash out.

    I do believe there are implementaions when try catch() blocks are acceptable maybe not for every block of code you write, but it does add stability - which is a very big issue to many programs. Don't over use it and use it on small code blocks to limit how much code must be rerun. It is a tool to use and when you run into resources that can be beyond your control such as external files it can default to a safe setting to allow the program to keep running.
    Dialogue class code for RPG

  10. #10
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    That said, in practice most compilers implement exceptions through `setjmp'/`longjmp' or similar.
    Outdated information.

    Nowadays, practically all compilers on modern platforms use the static table approach, also called zero-cost exceptions, which only incurs a runtime penalty if an exception is actually thrown. This includes GCC on just about all platforms (even Windows in newer versions), and Microsoft's compiler on x64 Windows. 32-bit Windows still uses the old way.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  11. #11
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by CornedBee View Post
    Outdated information.

    Nowadays, practically all compilers on modern platforms use the static table approach, also called zero-cost exceptions, which only incurs a runtime penalty if an exception is actually thrown. This includes GCC on just about all platforms (even Windows in newer versions), and Microsoft's compiler on x64 Windows. 32-bit Windows still uses the old way.
    In addition to this, if you handle errors by if's and return's, it has a lot of overhead as well for every conditional statement and return. It might even be slower than throwing.

  12. #12
    Registered User
    Join Date
    May 2009
    Posts
    64
    When I program in Java/C#, I use it most of the time.

    In C++, I have a current project right now that uses Ogre3D as their graphics renderer and I noticed that they use try.. catch most of the time. My current small 3D graphics engine has no try and catch on it. That's why I'm wondering if I should really make it just throw exception instead of the if..else statement or am I just lost. lol

    So, should I use try... catch? or try not to use it? Well, may I ask... do you use it?

    Thank you
    Sarah22

  13. #13
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    So, should I use try... catch? or try not to use it? Well, may I ask... do you use it?
    You should use exceptions if the situation calls for it.

    I use exceptions everywhere they are practicable.

    Instead of using exceptions to signal every unusual occurrence in your game, consider using return codes for most unusual occurrences and exceptions for cases that you can't recover from locally (say from within the primary "game loop"). One situation might be the loss of a packet versus the loss of the internet connection entirely. You could potentially recover locally from the lost packet. You should probably abort the game for the lost internet connection and only provide a message to the user as part of the caught exception.

    Nowadays, practically all compilers [...] if an exception is actually thrown.
    This is simply wrong unless you want to call a small percentage of compilers in the wild "practically all".

    *shrug*

    If you don't want to consider all the platforms GCC doesn't support, platforms GCC doesn't support anymore, platforms where GCC must be built with SJLJ exceptions, manufacturer provided compilers for a lot of embedded devices, most compilers for 32bit Windows compilers, and all small and embedded compilers I know of you should go for it.

    Or even if you just want to call development on 32bit Windows "outdated" you should go for it.

    I live here where only two (both GCC) of the two dozen compilers I have installed supports a table driven exception mechanism.

    Soma
    Last edited by phantomotap; 04-23-2010 at 09:55 AM.

  14. #14
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    What's "slow" is using the wrong tool for the job.
    Return values can be the wrong tool just as easily as exceptions can.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  15. #15
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Quote Originally Posted by EVOEx View Post
    In addition to this, if you handle errors by if's and return's, it has a lot of overhead as well for every conditional statement and return. It might even be slower than throwing.
    So basically we are saying that with the modern method exceptions overhead is comparable to that of an if statement?

    Is the statement then that try/catch is slow for compilers that use the modern version?

Popular pages Recent additions subscribe to a feed