How to get a message from compiler when incorrect string format is used

Viewed 222

Here is a piece of Delphi code that the compiler perfectly compiles :

Var S: String;

Begin
 S := Format('%s  %s', ['Hello']);
....

But on execution it raises an exception, of course there are two argument in the left string, and only one in the brackets...

Is there a way to have this error checked by the compiler and to be displayed at least as a warning, or better fatal error?

1 Answers

The compiler as currently written makes no effort to know about what's embedded between the quotes in the first parameter. It also doesn't count the values being passed in the second parameter, or have any idea whether they're correct. They're not evaluated until the function is called, where the exception is raised because they're incorrect. IOW, the compiler does not attempt to do anything that would allow it to issue such a warning or error.

When the function is called at runtime, it validates the number of arguments, whether they're the right type or not, and whether you've provided proper arguments. The compiler doesn't attempt to do that in any way. It only makes sure that you provide a string for the first parameter and an array of const for the second.

So to directly answer the question you've asked: No, there is no way to have the error checked by the compiler to have it issue a warning, because the compiler makes no effort to check anything that would allow it to do so.

Related