Know Your Bugs: Three
Kinds of Programming Errors
In
this lesson, you will learn about the different types of errors that can
occur when writing a program.
Even
the most experienced programmers make mistakes, and knowing how to debug an
application and find those mistakes is an important part of programming.
Before you learn about the debugging process, however, it helps to know the
types of bugs that you will need to find and fix.
Programming
errors fall into three categories: compilation errors, run-time errors, and
logic errors. The techniques for debugging each of these are covered in the
next three lessons.
Compilation Errors
Compilation
errors, also known as compiler errors, are errors that prevent your source
code from being converted into machine code. When you press the compile button, Java’s compiler reads the source code and
attempts to convert it into machine code.
If the compiler comes across code that it does not understand, it
issues a compiler error.
Most
compiler errors are caused by mistakes that you make when typing code. For
example, you might misspell a keyword, leave out some necessary
punctuation, or try to use an else if
statement without first using an if statement.
Fortunately,
when compilers issue errors, they include the error’s location and a
suggestion on the what may be the cause of the
error.
Run Time Errors
Run-time
errors are errors that occur while your program runs. These typically occur
when your program attempts an operation that is impossible to carry out.
An
example of this is division by zero. Suppose you had the following
statement:
speed
= miles / hours
If
the variable hours
has a value of 0, the division operation fails and causes a run-time
error. The program must run in order for this error to be detected, and if hours contains
a valid value, it will not occur at all.
One
useful tool to find the location of a run-time error is to include
temporary output statements that show the value of different variables at
different locations in the code.
Logic Errors
Logic
errors are errors that prevent your program from doing what you intended it
to do. Your code may compile and run without error, but the result of an
operation may produce a result that you did not expect.
For
example, you might have a variable named firstName that is initially set to a blank string. Later in your
program, you might concatenate firstName with
another variable named lastName to display a full name. If you forgot to assign
a value to firstName,
only the last name would be displayed, not the full name as you intended.
Logic
errors are the hardest to find and fix as their source is at times hard to
find. Proper code organization,
commenting and the use of output statements all help solve such problems.
|