Suppose, you write a Java program. There are different errors that may occur during compiling or executing it. We will divide all possible errors into two groups: compile-time errors and run-time errors.
Let's look at cases where the errors occur and how to avoid them.
Compile-time errors
- a syntax error: incorrect keyword, a forgotten symbol
;
at the end of a statement; - a bad source code file name;
- invoking a non-existing method;
- and many others.
public class MyClass {
public ztatic void main(String args[]) {
System.out.printn("Hello!");
}
}
There are two errors in this program:
- a typo in the keyword
static
; - incorrect name of the method
println
.
If you will fix these mistakes, it will be possible to compile this program.
To avoid such errors, programmers use modern IDE (Integrated Development Environment) with a static code analyzer. This tool allows programmers to identify compile-time errors before the compilation. In addition, it is able to highlight warn about more complex errors and weak places in your code, as well as tips on how to improve the code.
Over time, you will write code that contains less or even none of the compile-time errors.
Run-time errors
- logic errors - when a program produces a wrong result because of the code is not correct (for example, instead of "Hello!", your program outputs "Hi!");
- unhandled exceptional events like division by zero, not found file and other unexpected cases.
We will learn how to handle exceptional events (exceptions) in further lessons.
Avoiding such run-time errors is a more difficult task than avoiding compile-time errors. If your program compiles successfully, there are no guarantees that it does not have bugs. There are different strategies to find such errors:
- to debug your program;
- to write automatic tests for your program;
- to use code review practice as part of development process. In general, this practice stands for a case, when one or more developers visually inspect the source code of a program.