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

前端 未结 11 1668
旧巷少年郎
旧巷少年郎 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:28

    Note that if your code doesn't throw exceptions then it doesn't always imply that the input is within bounds. Relying on throwing exceptions by the standard Java (API + JVM), such as NullPointerException or ArrayIndexOutOfBoundsExceptions is a very unhealthy way to validate input. Garbage-in sometimes generates garbage-but-no-exception-out.

    And yes, exceptions are quite expensive. They should not be thrown during a normal processing flow.

提交回复
热议问题