What is the difference between a compile-time error and a runtime error in Java, and what does the compiler actually catch for you?
A compile-time error is one that the compiler finds before your program starts. A runtime error is one that happens while your program is already running.
The compiler catches a whole family of mistakes for you. It catches syntax mistakes, such as a missing semicolon or a missing brace. It catches type mistakes, such as giving a text value to a number variable. It catches a method that is called with the wrong number of arguments. It catches a method that promises to return a value but has a path that does not return one. And it catches a checked exception that you have not dealt with.
public class Main {
public static void main(String[] args) {
int x = 10;
int y = zero(); // this does not compile: the method does not exist
System.out.println(x + y);
}
}
A runtime error happens after all of that has passed. The program compiled, it started, and then something went wrong while it was working. The classic examples are a NullPointerException when you use an object that is null, an ArrayIndexOutOfBoundsException when you walk past the end of an array, and an ArithmeticException when you divide a whole number by zero.
The compiler cannot catch any of those, because it cannot know what the values will be while the program runs. A method can be perfectly correct for every value except one, and the compiler has no way of knowing which value will turn up.
Here is a rule of thumb that helps. If the mistake can be found by looking at the code alone, the compiler finds it. If the mistake depends on the data or on the state of the world at that moment, then it is a runtime error and you have to write the code so that it handles it.
The next question in this topic separates the two kinds of exceptions.