Thorough use of 'if' statements or 'try/catch' blocks?

前端 未结 9 1897
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 03:14

Give me some of your thoughts on which is a better coding practice/makes more efficient code/looks prettier/whatever: Increasing and improving your ability to use if statem

相关标签:
9条回答
  • 2021-01-12 04:06

    Regardless of what code you're writing, you'll end up using both. I can't speak for the Java runtime, but on the .NET runtime there's a performance hit associated with the use of try-catch blocks. As a result, I try to use them only in areas where I've got a clear way to handle the exception once caught (even if it's just logging the existence of a problem).

    If you find yourself using a lot of either try-catch blocks or if-else blocks in your code, or your methods tend to be rather long, consider refactoring the code into a larger number of smaller methods. The intent of your logic will be easier to follow--as well as easier to unit test.

    0 讨论(0)
  • 2021-01-12 04:08

    My 2p: Using try/catch is best:

    • it makes it absolutely clear to other coders that you are doing exception handling
    • the compiler understands what you are doing and can perform more appropriate compile-time checks for you

    In my experience, using if-conditional-logic makes it more difficult to distinguish error handling from business logic.

    0 讨论(0)
  • 2021-01-12 04:09

    if blocks are slightly faster; if you aren't going to need a dozen of them, they're a better idea than try/catches. Exceptions should be exceptional, not every time the code runs. I use Exceptions for rare events like server disconnections (even though they happen a few times every day), and if blocks for any of my controllable variables.

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