简体   繁体   中英

Java - When is it a compiler error and when is it a runtime exception?

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM