Is there any overhead in Java for using a try/catch block, as opposed to an if block (assuming that the enclosed code otherwise does not request so)?
For example, take the following two simple implementations of a "safe trim" method for strings:
public String tryTrim(String raw) {
try {
return raw.trim();
} catch (Exception e) {
}
return null;
}
public String ifTrim(String raw) {
if (raw == null) {
return null;
}
return raw.trim();
}
If the raw
input is only rarely null
, is there any performance difference between the two methods?
Furthermore, is it a good programming pattern to use the tryTrim()
approach for simplifying the layout of code, especially when many if blocks checking rare error conditions can be avoided by enclosing the code in one try/catch block?
For example, it is a common case to have a method with N parameters
, which uses M <= N
of them near its start, failing quickly and deterministically if any such parameter is "invalid" (e.g., a null or empty string), without affecting the rest of the code.
In such cases, instead of having to write k * M
if blocks (where k
is the average number of checks per parameter, e.g. k = 2
for null or empty strings), a try/catch block would significantly shorten the code and a 1-2 line comment could be used to explicitly note the "unconventional" logic.
Such a pattern would also speed up the method, especially if the error conditions occur rarely, and it would do so without compromising program safety (assuming that the error conditions are "normal", e.g. as in a string processing method where null or empty values are acceptable, albeit seldom in presence).
I know you're asking about performance overhead, but you really should not use try
/catch
and if
interchangeably.
try
/catch
is for things that go wrong that are outside of your control and not in the normal program flow. For example, trying to write to a file and the file system is full? That situation should typically be handled with try
/catch
.
if
statements should be normal flow and ordinary error checking. So, for example, user fails to populate a required input field? Use if
for that, not try
/catch
.
It seems to me that your example code strongly suggests that the correct approach there is an if
statement and not a try
/catch
.
To answer your question, I would surmise that there is generally more overhead in a try
/catch
than an if
. To know for sure, get a Java profiler and find out for the specific code you care about. It's possible that the answer may vary depending on the situation.