0

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

Community
  • 1
  • 1
Jordi Castilla
  • 24,953
  • 6
  • 58
  • 97
  • 2
    `instanceof` is the better way – Jens Jan 27 '15 at 10:30
  • You may want to read http://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control – Evan Knowles Jan 27 '15 at 10:32
  • 2
    Why test at all? If `is` is in both cases downcastable to an `InputStream` then just write `InputStream is = fileItem.getInputStream()` – Alnitak Jan 27 '15 at 10:32
  • Both seems like a code smell to me, if you care about the specific concrete type - you should carry it all the way. – amit Jan 27 '15 at 10:33
  • I'm reopening as a this is not a "simple control flow", the usage of `instanceof` as the suggested alternative has much more flaws (and thus depth to the question) than a simple "control flow" alternative. – amit Jan 27 '15 at 10:36

2 Answers2

2

The more general rule for exception would be to avoid them if they can also be expressed by a more simple construct like an if.

generating an exception is expensive! it needs to collect the call stack - and depending on you application complexity - this alone can be a horrible source of garbage on your heap, which needs to be cleaned up by the GC.

light_303
  • 2,051
  • 2
  • 16
  • 32
  • When deciding whether to use exceptions or other control flow constructs, I don't think that size of call stack, heap memory and GC performance should be the primary concerns. – aioobe Jan 27 '15 at 10:36
1

In general, prefer RTTI (i.e. instanceof) over exception handling.

However in this case your test is completely unnecessary. Since it appears you only want an InputStream and don't actually care which specific type it is, just write:

InputStream is = fileItem.getInputStream();

You only need to specialise to one of the derived subclasses of InputStream if you wish to invoke special methods that don't exist in the base class.

Alnitak
  • 313,276
  • 69
  • 379
  • 466