Reputation: 421
Consider the following try/catch block:
try {
throwCheckedException();
} catch (IOException e) {
doStuffWithException(e);
}
In the above block, throwCheckedException
has a chance of throwing a checked exception, so I need a catch clause that calls doStuffWithException
. However, say I want to add an additional statement to this block:
if (!someBoolean) {
throw new IOException("someBoolean must be true, got false.");
}
Should I utilize the catch block and simply insert the above code into the try block, or would it be better practice to duplicate what's in the catch block, like what's show below?
try {
throwCheckedException();
if (!someBoolean) {
doStuffWithException(
new IOException("someBoolean must be true, got false.")
);
}
} catch (IOException e) {
doStuffWithException(e);
}
Upvotes: 0
Views: 484
Reputation: 4365
Throwing exception is expensive operation. So, if you considering two alternatives - throwing and not throwing, then not throwing is preferable way.
However, using exception as input parameter to doStuffWithException
in try-block
, feels like a code small. So, I would suggest to refactor exception handling logic to not depend on exception as input parameter.
If you handle exceptional situation depending on some data in exception - extract that data and pass to handle
method. Basically, do not use exception as DTO or POJO (as exceptions are not intended for this purpose).
Summarizing, I suggest to have something like following snippets:
try {
throwCheckedException();
if (!someBoolean) {
Data data = createData();
handle(data);
}
} catch (IOException e) {
Data data = createDataFromMessage(e.getMessage());
handle(data);
}
Alternatively, to reduce nesting inside try-block
:
try {
throwCheckedException();
} catch (IOException e) {
Data data = createDataFromMessage(e.getMessage());
handle(data);
}
if (!someBoolean) {
Data data = createData();
handle(data);
}
Upvotes: 2