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

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

    I could find surprisingly little current information about the cost of throwing Exceptions. Pretty obviously there must be some, you are creating an object, and probably getting stack trace information.

    In the specific example you talk about:

    if (value1 == badvalue || value1 == badvalue2 || ...) {
          result = specificError;
     } else {
          DoSomeActionThatFailsIfValue1IsBad(value1);
          // ...
          result = success;
     }
    

    The problem for me here is that you are in danger if (probably incompletely) replicating logic in the caller that should be owned by the method you are calling.

    Hence I would not perform those checks. Your code is not performing an experiment, it does "know" the data it's supposed to be sending down I suppose? Hence the likelyhood of the Exception being thrown should be low. Hence keep it simple, let the callee do the checks.

提交回复
热议问题