Sometimes, to avoid using if
I create code that throws exception to parse some values.
For example: When you have an input field where you can write a partner number or a partner name to search, I do like:
try {
Integer.parseInt(string);
// use the input as int
} catch (NumberFormatException) {
// use the input as a String
}
Now I have a similar problem, but with InputStream
.
InputStream is;
try {
is = (FileInputStream) fileItem.getInputStream();
} catch (ClassCastException e) {
is = (ByteArrayInputStream) fileItem.getInputStream();
}
My question is: Is better do it in that way throwing the exception
or maybe an if with instanceof
like:
InputStream is;
if (fileItem.getInputStream() instanceof FileInputStream) {
is = (FileInputStream) fileItem.getInputStream();
} else if (fileItem.getInputStream() instanceof ByteArrayInputStream) {
is = (ByteArrayInputStream) fileItem.getInputStream();
}
And WHY?
I've found similar problems here or here but there are not exact