Which is better/more efficient: check for bad values or catch Exceptions in Java

前端 未结 11 1664
旧巷少年郎
旧巷少年郎 2020-12-15 08:11

Which is more efficient in Java: to check for bad values to prevent exceptions or let the exceptions happen and catch them?

Here are two blocks of sample code to ill

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 08:47

    "How does your answer change if the value is "bad" (would throw an exception) most of the time?" I think that's the key right there. Exceptions are expensive as compared to comparisons, so you really want to use exceptions for exceptional conditions.

    Similarly, your question about how this answer might change depending on the language/environment ties into that: The expense of exceptions is different in different environments. .Net 1.1 and 2.0 are incredibly slow the first time an exception is thrown, for instance.

提交回复
热议问题