Reputation: 2183
For example i have the following code
class Format{
public static void main(String[] args) {
String formated = String.format( "%c",-42); //I have -42 as second argument.
System.out.println(formated);
}
}
I know this is very bad as it throws IllegalFormatCodePointException but question that struck to my mind is that why compiler is not complaining here,if it can complain at
char c = -42;
So,knowing that the upper code produces an exception,Why compiler just sit and watch?
Upvotes: 3
Views: 161
Reputation: 719576
So, knowing that the upper code produces an exception. Why compiler does just sit and watch?
Because the Java Language Specification says it should.
The type signature for the format
method is format(String format, Object... args)
, and the JLS says that the if the arguments conform to that signature after application of prescribed conversions then the code is valid. The compiler is NOT ALLOWED to say "compilation error" for your code ... because the code is valid Java code.
In fact, the only way that the compiler could "know" that the your code will always produce an exception is if it is coded with special knowledge of what format strings mean. And, in that case, the most that a (hypothetical) compiler with that special knowledge would be allowed to do would be to output a Warning.
In reality, this kind of thing is treated as beyond the scope of a typical compiler. Rather it is the problem domain of static analysis tools such as FindBugs and PMD. (Or for the C language, the Lint tool ... which IIRC does check format strings in some versions.)
Upvotes: 2
Reputation: 382454
There's no facility at the language level to define this type of constraint.
What the compiler can check is that the type of the arguments is the one defined by the method prototype :
public static String format(String format, Object... args)
You can see it's extremely dynamic and that you can pass sometimes an int, and sometimes somethings's else, which can be convenient, especially as some format strings are able to handle for various types. The format string itself could also be dynamically provided.
I don't know any language implementing printf
and able to statically check that. It's such a specific feature that it's always implemented using the language, not at the language definition level.
Upvotes: 2