AbdullahR AbdullahR - 1 year ago 45
Java Question

What is the difference between run-time error and compiler error?

In one of my prof slides on ploymorphism, I see this piece of code with a couple of comments:

discountVariable = //will produce
(DiscountSale)saleVariable;//run-time error
discountVariable = saleVariable //will produce
//compiler error

As you can see, it says in the first casting statement that it'll produce run-time error and in the other one it says it'll produce compiler error.

What makes these errors? and how they differ from each other?

Answer Source

A run time error will only occur when the code is actually running. These are the most difficult - and lead to program crashes and bugs in your code which can be hard to track down.

An example might be trying to convert a string: "hello" into an integer:

string helloWorld = "hello";
int willThrowRuntimeError = Convert.ToInt32(helloWorld);

The compiler may not see this as a problem but when run an error will be thrown.

Compiler errors are due to inaccuracies in code, where the compiler throws an error to alert you to something which will not compile, and therefore cannot be run.

An example of a compiler error would be:

int = "this is not an int";

Hope that helps.