Program errors usually include: syntax errors , logic errors , and operating abnormalities .
The following are introduced respectively:
1. Syntax error:
Needless to say, everyone must know from previous studies that if the program code does not meet the grammatical requirements, the compiler will prompt an error during compilation and linking, which is easy to find.
2. Logical errors:
In this case, it means that there is no problem with compilation, no errors, and it can be run. However, the output result or execution process of the program is not as expected and cannot achieve the expected results. This kind of error is called a logic error and requires continuous debugging and testing to discover.
3. Operation abnormality:
Running exception (exception) refers to the abnormal termination of the program due to unexpected circumstances during the running process, such as insufficient memory, open files that do not exist, division by 0, etc.
We already know the first two, and the third is what we will explain in detail in this chapter. Under normal circumstances, although program exception errors cannot be avoided, they can be anticipated and predictive processing can be carried out to avoid program crashes and ensure the robustness of the program. This behavior is called exception handling .
In past studies, we have many ways to capture and handle exceptions, such as judging the return value of the calling function through if...else, or checking key data before executing the code, etc. If a problem occurs, use exit () or abort() functions to terminate the program.
for example:
cin>>a>>b;if(b==0)//Catch exception{cout<<Drivide0!<<endl;}else{cout<<a<</<<b<<=a/b<< endl;}
As you can see, in past studies, we often use if to make judgments to capture and prevent key parts. However, this method often makes the program less readable due to too many if judgments during use. Reduced, and when it is necessary to determine the return value of a function, we are helpless for those functions that do not return a value. For this reason, C++ provides us with an exception handling solution.