Results tagged “Compiler”

A recent blog entry posted in Argonauts blog deals with a C# codepiece which is valid at the first look and even compiles cleanly but failes gracefully with a runtime exception when executed.

Argo shows the C# code for his example but (as he also mentions) the same code can be used in a Java example. The following class hirarchy...

class BaseType {
}

class SubTypeA : BaseType {
}

class SubTypeA : BaseType {
}

looks innocent so far. But if it is used the following way

public static void main(String[] args) {
  BaseType[] baseArray = new SubTypeA[3];

  baseArray[0] = new BaseType();
  baseArray[1] = new SubTypeA();
  baseArray[2] = new SubTypeB();
}

things get interesting. The code compiles without any problems (as in C#) but when executed, one is faced with an java.lang.ArrayStoreException. The cause for this is burried in the Java Language Specification 4.6 (thanks for the hint in the posts comments which saved me some searching). Upon compilation the type of the array is BaseType and after that it gets the SubTypeA-array assigned. The compiler does not know at this position that it would have to re-type the array it is assigning to to avoid the problems lying ahead. That's why arrays are also checking their assigned objects at runtime and cause this exception if something invalid occours (as specified in JLS 4.7).

I think that this problem would be solvable in Java, C# and most other languages which treat arrays the same way. But I also think that this would open a pandoras box ful of problems and complexity arising from this new constraint just for this specific issue. And personally I think this issue is not a common one and appears just in border-cases so that most developers can deal with it for now. Nevertheless I also think, this issue can be solved, it just may be too late for Java and C#.

|

1

Archives