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

风流意气都作罢 提交于 2019-12-28 18:44:40

问题


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?


回答1:


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)




回答2:


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

  • Is 1/0 a legal Java expression?
  • What is the difference between javac and the Eclipse compiler?



回答3:


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



来源:https://stackoverflow.com/questions/3179504/java-when-is-it-a-compiler-error-and-when-is-it-a-runtime-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!