If you are new to programming, it is important to learn how to interpret and respond to errors that may occur when you try to compile a program. Most compilation errors are caused by typing mistakes. As all programmers soon find out, it is quite easy to accidentally type something incorrectly. Fortunately, if you type something wrong, the compiler will report a syntax error message when it tries to compile your program. This message gives you the line number at which the error is found and a description of the error, itself.
Although the syntax errors reported by the compiler are, obviously, helpful, they sometimes can also be misleading. The C# compiler attempts to make sense out of your source code no matter what you have written. For this reason, the error that is reported may not always reflect the actual cause of the problem. In the preceding program, for example, the accidental omission of the opening curly brace after the Main( ) method generates the following sequence of errors when compiled by the csc command-line compiler. (Similar errors are generated when compiling using the IDE.)
Example.cs(12,21): error CS1002: ; expected Example.cs(13,22): error CS1519: Invalid token '(' in class, struct, or interface member declaration Example.cs(15,1): error CS1022: Type or namespace definition, or end-of-file expected
Clearly, the first error message is completely wrong, because what is missing is not a semicolon, but a curly brace. The second two messages are equally confusing.
The point of this discussion is that when your program contains a syntax error, don’t necessarily take the compiler’s messages at face value. They may be misleading. You may need to “second guess” an error message in order to find the problem. Also, look at the last few lines of code immediately preceding the one in which the error was reported. Sometimes an error will not be reported until several lines after the point at which the error really occurred.
No comments:
Post a Comment