Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

Difference between Run time and Compile time error

Hi,


Can you please explain runtime and compile time error with examples.

When it comes to compiling and running a Java program, there are two actors involved - the compiler and JRE. The compiler converts your java program (the text file) to a byte code the JRE can run. This is why you need to compile the program before you can run it.


Compile errors happen for two given reasons:


1) Your program is syntactically wrong, making the compiler unable to convert it to the byte code format. For example:


class ErrorDemo {
   public doStuff() { }
} 


In the above program, what does doStuff() return? It's not even void, so the compiler can't understand what you are trying to do with it, and so it can't convert this to a byte code.


2) To prevent you from getting runtime errors. Yes - these errors are deliberately caused to protect you from getting run time errors which would fail the program at runtime if allowed. This is because runtime errors are harder to find and debug, as one would have no idea when a runtime error would occur until it occurs on a given circumstance. Compile errors, on the other hand, are pretty static in nature, and you can find all the compile errors just by attempting to compile the program. So, again, to prevent you from getting those unfriendly runtime errors, the compiler sometimes causes errors. Here's an example.


class A { }
class B { }
class C { 
   void doMethod() {
       A object = new B();
   }
}


In the above assignment statement, you are just trying to assign an object of B to a reference of A. If compiler allowed you to do this, you would get a runtime error somewhere in your code when it tries to call the doMethod() method. If the method doMethod() is not something that gets called often, you wouldn't even notice this error until whenever it gets called. So, to prevent that, the compiler causes an error as it is obvious for the compiler that this will definitely cause an error.


Runtime exceptions, on the other hand, are those that the compiler couldn't detect at the first place. Here's a simple example.


public void doMethod() {
   int x = 0;
   int y = 0 / x;
} 


Obviously we, as humans, can see that we are trying to divide 0 by 0, which is a mathematically wrong (indeterminate) and therefore causes an error. But it's not the compiler's job to actually do the calculation. It's only the JRE that can do the calculation. For this reason, the compiler can't spot this error at the first place. But at the runtime, the JRE faces the trouble, and fails with an ArithmeticException.


ExamLab © 2008 - 2024