C++ Error Handling
There are 5 major type of errors in C++.
- Syntax Errors: When we use incorrect syntax when writing a program it leads to a syntax error.
Missing of semicolon or parenthesis or any other violation of the C++ syntax will lead to this error. Consider the following example:
- Runtime Errors Errors that occur during program execution after successful compilation are called run-time errors. One of the most common run-time errors is division by zero also known as Division error. These types of errors are difficult to find as the compiler doesn’t point to the line at which the error occurs.
Example of a runtime error
- Linker Errors:These errors occur when the executable of the program cannot be generated. This may be due to wrong function prototyping, or incorrect header files
Consider this piece of code
- Logical Errors: On compilation and execution of a program, we do not obtain the desired output for certain input values. These types of errors that provide incorrect output but appear to be error-free are called logical errors. These are the most common errors done by beginners of programming.
Example of a logical error:
- Semantic Errors: This error occurs when the statements written in the program make no sense to the compiler.
Error Handling
When executing C++ code, different errors may occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message. The technical term for this is: C++ will throw an exception (throw an error).
Exception handling in C++ is carried out by 3 keywords try , throw and catch
The try statement will allow you to define a block of code to be tested for errors while it is being executed.
The throw keyword will throw an exception when a problem is detected, which lets us create a custom error.
The catch statement will allow you to define a block of code to be executed if an error occurs in the try block.
The try and catch keywords always come in pairs:
Syntax:
Example demonstrating exception handling in C++
We use the try block to test some code: If the age variable is less than 18, we will throw an exception, and handle it in our catch block.
In the catch block, we catch the error and do something about it. The catch statement takes an argument: in our example, we use an int variable myage (because we are throwing an exception of int type in the try block, to output the value of age.
If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater than 18), the catch block is skipped.