-3

I am new to programming and want to know about does try/catch affects performance if no exception thrown in try block?

  • Can't you take 10 minutes to write a test and benchmark it to answer this yourself? – Ken White Mar 24 '17 at 22:13
  • 2
    Here you can find some stats in this answer: http://stackoverflow.com/questions/1308432/do-try-catch-blocks-hurt-performance-when-exceptions-are-not-thrown – mako Mar 24 '17 at 22:16
  • 1
    Don't make the mistake of assuming java and C# will have the same answer. – itsme86 Mar 24 '17 at 22:19
  • 1
    Possible duplicate of [Do try/catch blocks hurt performance when exceptions are not thrown?](http://stackoverflow.com/questions/1308432/do-try-catch-blocks-hurt-performance-when-exceptions-are-not-thrown) –  Mar 24 '17 at 22:34
  • If you're new to programming then try/catch is the last place you should worry about performance. Far more important are the algorithms you choose because those can affect the performance of your code by factors of a thousand, and more important than that is learning how to write correct and readable code. – Ray Fischer Mar 24 '17 at 22:52

3 Answers3

2

No, it does not.

Because the catch block will not executed if no exception happen so it does not affect performance.

So consider i have this piece of code :

try {
    Integer.parseInt("123");
} catch (NumberFormatException e) {
    while (true) {
        System.out.println("Error");
    }
}

The catch block run an infinite loop, so this can affect the performance, but when this happen? it happen IF the number is not an Integer it throw an exception, so it can execute the catch block and in this case it will affect performance.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

Yes, Try-Catch affect your performance.

For more information please check this link (from MSDN).

The link is helpful, but its contents with regard to exceptions is the opposite of your "Yes" answer.

"Finding and designing away exception-heavy code can result in a decent perf win. Bear in mind that this has nothing to do with try/catch blocks: you only incur the cost when the actual exception is thrown. You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance"

schulmaster
  • 413
  • 5
  • 16
Fatikhan Gasimov
  • 903
  • 2
  • 16
  • 40
0

There will be some setup code that needs to run, eg. in Java a try block installs itself into a special table (which the JVM looks at if an exception is thrown), but this should be insignificant. The expectation is that try/except has no overhead when exceptions are not thrown.

thebjorn
  • 26,297
  • 11
  • 96
  • 138