Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can not Java multi-catch deal with types that is related by subclassing?

Here is a piece of code that shall not compile:

void multiCatch()
{
    try {
        throwIOFile();
    }
    // FileNotFoundException extends IOException, hence this
    // does not compile ("alternatives" related by sub classing):
    catch (IOException | FileNotFoundException e) { }
}

void throwIOFile() throws IOException, FileNotFoundException
{}

Everything works like a charm had not the exception types been related by sub classing. If you swap the IOException in my code snippet for say.. SQLException, it works. The specification reads:

It is a compile-time error if a union of types contains two alternatives Di and Dj (i ≠ j) where Di is a subtype of Dj.

I can not understand the rationale behind this. Granted, the multi-catch in my example is completely redundant since I could just as well catch an IOException only. But what would be the harm in making my code snippet legal? Surely there has to be a harm for a practice to become illegal?

like image 219
Martin Andersson Avatar asked Nov 06 '13 17:11

Martin Andersson


1 Answers

Having subclasses of a given exception in the same catch simply doesn't make any sense and it's confusing, because you're going to enter the catch anyway no matter the subclasses you specify. For example, why are you going to write

catch (IOException | FileNotFoundException e)

if

catch (IOException e)

will have the exact same behavior? It's simply confusing.

like image 152
m0skit0 Avatar answered Sep 20 '22 08:09

m0skit0