I am currently studying for the SCJP certification using the Sierra and Bates Study Guide and in many of the self tests (mock exam questions) I keep running into the same problem - I can't tell whether a particular error will be at runtime (an exception) or at compile (compile error). I know this is a bit of a vague question and that it might not be possible to answer but, how can I tell if an error will be found at compile or at runtime? Would you be able to send me some website links that might be able to help me?
Compile time error - the java compiler can't compile the code, often because of syntax errors. Typical candidates:
- missing brackets
- missing semicolons
- access to private fields in other classes
- missing classes on the classpath (at compile time)
Runtime error - the code did compile, can be executed but crashes at some point, like you have a division by zero.
- using variable that are actually
null
(may cause NullPointerException) - using illegal indexes on arrays
- accessing resources that are currently unavailable (missing files, ...)
- missing classes on the classpath (at runtime)
('Crashes' is really not the correct term and is only used to illustrate what happens)
There is no easy answer to this; to see if something will compile, you have to completely understand the language specification and the API involved. You essentially have to act like a compiler, and no one can do this perfectly. Even compilers don't always follow the specification perfectly.
There are many, MANY corner cases in the Java language. This is why things like Java Puzzlers are so intriguing: people can't always tell if something would even compile and/or if it does, what's really going on.
Some of the more complicated areas of the Java language are:
- Generics (Eclipse and
javac
compiler can't even agree on everything) - Method overloading resolution (one of the hardest to understand section of JLS)
Related questions
instanceof
is a compile-time error vs and when it throws ClassCastException
, perhaps? Search around and perhaps that's already asked/answered, but in any case JLS 15.20.2 is quite clear on how it should behave (java.sun.com/docs/books/jls/third_edition/html/…) –
Overfly Basically Runtime errors are logical errors in your code, even if the code is syntactically correct. Compiler errors refer to errors in your syntax/semantics. If you have a compiler error in your code, the program will never get to run (and check the logic of the code). If you have both syntactic and logical errors, you will first get the compiler error (syntax error) and then when you run the code again you will get a runtime error (logical error).
© 2022 - 2024 — McMap. All rights reserved.