Compile time vs run time errors [duplicate]

喜欢而已 提交于 2019-12-09 18:46:00

问题


Possible Duplicate:
Runtime vs Compile time

How should I know whether a specific line of code in Java may throw a compile time or run-time error? Assuming that the specific line of code anyway throws and error.


回答1:


In Eclipse, compile time errors will be underlined in red. A compile time error is an error that is detected by the compiler. Common causes for compile time errors include:

  • Syntax errors such as missing semi-colon or use of a reserved keyword (such as 'class').
  • When you try and access a variable that is not in scope.
  • When you declare multiple objects with the same name.

If the compiler detects any errors during compilation it will fail to build a new assembly (or class file in Java).

Even if your code has no compile time errors, errors can still occur on run-time. Errors such as 'logic errors' and 'runtime errors'. A good example of a runtime error is as followed:

  • Pretend you're going to store an item in an array at index 5 but the array's size is only 4. The compiler won't detect an error here because it understands that the array size is subject to change but on run-time you'll be thrown an exception.

To detect which line exactly a run-time error occurs on you can use a combination of break points in Eclipse and proper exception handling.




回答2:


To see if your code doesn't compile, try to compile it. The compiler will complain.

To see if your code contains runtime errors, write unit tests.




回答3:


Practically every line of code may in theory throw a runtime exception and there is no such thing as "throwing a compile-time error". I believe you have mixed up compiler errors with runtime exceptions.

Anyway, the compiler errors are easy: compile it and see. There is never any "may" about them: a line of code definitely will, or will not, produce a compiler error.

As for a runtime error, the best you can do is statically analyze and guess whether a line of code will result in an error. Some cases are dead obvious, such as throw new RuntimeException() or null.toString(), but most aren't and require great experience to analyze without executing.




回答4:


The best way would be to compile it, then most of the compilers will point out all of the compile-time errors. Run-time errors on the other hand require greater effort from the developer.

Some compilers inform the user of the exceptions that maybe thrown, but the best way to find if a particular line of code contains run-time is run them with different inputs and observe the results(i.e use Unit Tests, sanity tests etc).




回答5:


When you compile your code, you will see wether there's a compile time error. Running the code might show runtime errors.



来源:https://stackoverflow.com/questions/12882448/compile-time-vs-run-time-errors

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