1

I know it is a probable duplicate of this question. But the answer to that question includes the | inside the catch (..|..) which is unsupported in the earlier Java versions. I am bound to use an old version though. I have the same response to any type of exception. So, I would like to combine my catch statements in one, like this:

try {...}
catch(Excetion1 e1 OR Exception2 e2 OR etc)
{
...
}

I tried to use the hash | instead of OR, with no result. Is there any work around for older Java versions?

Community
  • 1
  • 1
Buras
  • 3,069
  • 28
  • 79
  • 126

3 Answers3

5

Quoting the documentation:

In Java SE 7 and later, a single catch block can handle more than one type of exception

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

If it doesn't work for you, make sure you're using the Java 7 JRE.

Mifeet
  • 12,949
  • 5
  • 60
  • 108
2

in java 6: no

in java 7, yes:

catch( Exception1 | Exception2 e )
Vegard
  • 1,802
  • 2
  • 21
  • 34
1

If you have same response for all Exceptions then you can simply use

try {...}
catch(Exception ex)
{
...
}
stinepike
  • 54,068
  • 14
  • 92
  • 112
  • 1
    this solution is right for me...it looks nice...i hope it works on the older versions. – Buras May 31 '13 at 20:39
  • 1
    catching Exception is not a good solution imo. if that is needed it is very often a symptom of a bad application design. I will advice you to create your own set of exceptions if it is a big project. For smaller projects handle the exceptions thrown separately, don't catch all in one catch. – Vegard May 31 '13 at 20:48
  • @Vegard, thank you for advice (+1). i am dealing with a web application. the exceptions are different but...all i need is a shortcut for the time being...till i switch java versions – Buras May 31 '13 at 20:59