Is there an easy way to work out whether the program will throw a compilation or a runtime error. Im sure that runtime errors are from objects after they have initialised however i can't find much on the fundamental difference (apart from the fact that one is done at compile time and the other at run time) as to why a program would throw one and not the other and was wondering if anyone had any good tips on it Even though this is a bit hard to explain but I will try...
The general rule of thumb is this -
Compiler errors are usually syntax errors. That is to say, whatever the compiler can catch pertaining to the general syntax as specified by the language specification... such as incompatible operands, incorrect syntax of constructs... etc.
Runtime exceptions are the ones which depend on the values of the variables/objects determined at Runtime. A perfect candidate for this is with Conversion & Casting. Consider the following example -
class Base {}
class Sub extends Base {}
class Unrelated {}
public class MyTest {
public static void main(
String[] args) {
Base b = new Base();
Base b1 = new Sub(); // ok. Valid Conversion
Sub s = new Sub();
Unrelated ur = new Unrelated();
b = s; //ok. Valid conversion.
ur = b; // Compile Time error. Incompatible references
s = b; // Compile Time error. Compatible references but cannot assign a base class reference to a subclass reference
s = (Sub)b; // Will not fail at compile time. Since the programmer is instructing the compiler to overlook this... thereby procastinating the check till Runtime. Since b, at runtime, points to a Base class object, it will fail at Runtime with a ClassCastException.
s = (Sub)b1 // This will pass both at compile time and runtime. No exception will be thrown since, at runtime, the reference b1 points to a subclass object.
}
}
Hope it helps.