Error Handling

In C++, there are many different ways of classifying errors, but they can be boiled down to four categories:

  • Compile-time errors: Errors found by the compiler.

  • Link-time errors: Errors found by the linker when it is trying to combine object files into an executable program.

  • Run-time errors: Errors found by checks in a running program.

  • Logic errors: Errors found by the programmer looking for the causes of erroneous results.

Compile-time Errors

There are two types of compile-time errors:

  • Syntax errors: Errors that occur when we violate the rules of C++ syntax.

  • Type errors: Errors that occur when there are mismatch between the types we declared.

Sometimes the code compiles fine, but there is still a message because the program needs some function or library that it can’t find. This is known as a link-time error.

As our program gets bigger, it is good practice to divide the program into separate files. After compiling them, the linker takes those separate object files and combines them into a single executable file. Link-time errors are found by the linker when it is trying to combine object files into an executable file.

Run-time Errors

If our program has no compile-time errors and no link-time errors, it’ll run. This is where the fun really starts.

Errors which happen during program execution (run-time) after successful compilation are called run-time errors. Run-time errors occur when a program with no compile-time errors and link-time errors asks the computer to do something that the computer is unable to reliably do.

Some common run-time errors:

  • Division by zero also known as division error. These types of error are hard to find as the compiler doesn’t point to the line at which the error occurs.

  • Trying to open a file that doesn’t exist

Logic Errors

Once we have removed the compile-time errors, link-time errors, and run-time errors, the program runs successfully. But sometimes, the program doesn’t do what we want it to do or no output is produced. Hmmm…

These types of errors which provide incorrect output, but appears to be error-free, are called logical errors. These are one of the most common errors that happen to beginners and also usually the most difficult to find and eliminate.

Logical errors solely depend on the logical thinking of the programmer. Your job now is to figure out why the program didn’t do what you wanted it to do.

Some common logic errors:

  • Program logic is flawed

  • Some “silly” mistake in an if statement or a for/while loop