Should java try blocks be scoped as tightly as possible?

后端 未结 7 1779
孤城傲影
孤城傲影 2020-12-01 00:35

I\'ve been told that there is some overhead in using the Java try-catch mechanism. So, while it is necessary to put methods that throw checked exception within a try block t

相关标签:
7条回答
  • 2020-12-01 01:10

    Putting the try blocks around the specific code that may throw an exception, makes it, in my opinion easier to read. You're likely to want to display a different message for each error and provide instructions to the user, which will be different depending on where the error occurs.

    However, the performance issue that most people refer to is related to raising the exception, not to the try block itself.

    In other words, as long as you never have an error raised, the try block won't noticeably affect performance. You shouldn't consider a try block just another flow control construct and raise an error to branch through your code. That's what you want to avoid.

    0 讨论(0)
  • 2020-12-01 01:17

    No. The only thing that you should be considering is where you can reasonably handle the exception and what resources you need to reclaim (with finally).

    0 讨论(0)
  • 2020-12-01 01:23

    The second method will generate a compiler error that reader may not have been initialized. You can get around that by initializing it to null, but that just means you could get an NPE, and there's no advantage to that.

    0 讨论(0)
  • 2020-12-01 01:28

    This is premature optimization at its worst. Don't do it.

    "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" - Knuth.

    0 讨论(0)
  • 2020-12-01 01:29

    I've been told that there is some overhead in using the Java try-catch mechanism.

    Absolutely. And there's overhead to method calls, too. But you shouldn't put all your code in one method.

    Not to toot the premature optimization horn, but the focus should be on ease of reading, organization, etc. Language constructs rarely impact performance as much as system organization and choice of algorithms.

    To me, the first is easiest to read.

    0 讨论(0)
  • 2020-12-01 01:29

    there is very very little benefit to the 2nd method. after all if you can successfully open a file but not read from it, then there is something very wrong with your computer. thus knowing that the io exception came from the readLine() method is very rarely useful. also as you know, different exceptions are thrown for different problems anyway (FileNotFoundException, etc)

    as long as you scope it with a 'logical' block, ie opening, reading, and closing a file in 1 go, i would go with the first method. it's much simpler to read and, especially when dealing with IO, the processor cycles used by the try-catch overhead would be minimal if any.

    0 讨论(0)
提交回复
热议问题