Exception handling in C++

  • 2020-04-02 01:28:17
  • OfStack

Errors in programs are divided into compile-time errors and run-time errors. Compile-time errors are mainly syntax errors, such as no semicolon at the end of a sentence, mismatching parentheses, keyword errors, etc. These errors are relatively easy to correct, because the compilation system will indicate the error in the line, what error. Runtime errors, on the other hand, are not easy to fix because they are unpredictable or predictable but unavoidable, such as running out of memory or array overbounds when calling functions. If these errors are not taken effective preventive measures, then often will not get the correct results of the operation, abnormal program termination or serious will appear a crash phenomenon. We call the errors of the program runtime as exceptions and the handling of exceptions as exception handling. The exception handling mechanism provided in C++ has a clear structure, which guarantees the robustness of the program to some extent.

The process of handling exceptions in C++ is as follows: when an exception occurs in the executing program, it can not be handled in this function, but it throws an error message, which is passed to the function at the next higher level to solve it. If this level of upload is not handled at the highest level, the running system will automatically call the system function terminate, which calls abort. Such an exception handling approach separates the exception raising and handling mechanisms from handling them in the same function. This allows the underlying function to solve the actual task without having to worry too much about handling the exception, leaving the task of handling the exception to the upper function.

The C++ exception handling mechanism has three parts: try(check), throw(throw), and catch(catch). The statements that need to be checked are placed in the try module to check for errors, throw an exception, issue an error message, and catch catches and handles the exception information. Throw typically throws an exception that matches the type of exception caught by catch. The general format of exception handling is:


  try
  {
 Checked statement 
    throw  abnormal 
  }
  catch( Exception types 1)
  {
 Statement for exception handling 1
  }
  catch( Exception types 2)
  {
 Statement for exception handling 2
  }
  ...

Here's an example of exception handling:

#include "stdafx.h"
#include <iostream>
template <typename T>
T Div(T x,T y)
{
if(y==0)
throw y;//An exception is thrown
return x/y;
}
int main()
{
int x=5,y=0;
double x1=5.5,y1=0.0;
try
    {
//The statement being checked
        std::cout<<x<<"/"<<y<<"="<<Div(x,y)<<std::endl;
        std::cout<<x1<<"/"<<y1<<"="<<Div(x1,y1)<<std::endl;
    }
catch(int)//Exception types
    {
        std::cout<<" Dividing by 0, Calculation error! "<<std::endl;//Exception handling statement
    }
catch(double)//Exception types
    {
        std::cout<<" Dividing by 0.0, Calculation error! "<<std::endl;//Exception handling statement
    }
return0;
}

Results:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201308/2013082009365510.jpg ">

Looking at the sample code above, one might ask that the division calculation of the second double precision type should also throw an exception, which is not the case in the actual operation. In fact, the double precision type division function has never been executed. The execution procedure of the above program is as follows: when the function Div(x,y) is called, an exception occurs. The statement "throw y" in the function Div throws an exception. The return x/y is not executed. So the Div(x1,y1) and catch(double){} modules are not executed at all. If we change the value of y to 1, the result becomes:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201308/2013082009365511.jpg ">

If no exception occurs when the try statement module is executed, the catch statement block does not work, and the process moves to the statement that follows to continue execution. From the above two results, we can see that the first throw throws an int, so we can find a catch that handles this type, and the second throw a double, and we can find a catch that handles this type.

Following are some additional points for exception handling :(1) the try and catch blocks must be enclosed in curly braces. (2)try and catch must appear in pairs. A try_catch result can only have one try block, but can have multiple catch blocks to match with different exception information. (3) if the type of exception information is not specified in the catch block, the truncation number "..." is used instead. , means it can capture any type of exception information; (4) if throw does not include any expression, it means that it throws the exception information that is currently being processed again and passes it to the catch at the next level for processing; (5) once an exception is thrown in C++, if the program does not capture anything, the system will automatically call a system function, terminate, which calls abort.

Finally, I'll summarize today's lecture with an example (development tool: vs2010):


#include "stdafx.h"
#include <iostream>
template <typename T>
T Div(T x,T y)
{
if(y==0)
throw y;//An exception is thrown
return x/y;
}
int main()
{
int x=5,y=1;
double x1=5.5,y1=0.0;
try
    {
//The statement being checked
        std::cout<<x<<"/"<<y<<"="<<Div(x,y)<<std::endl;
        std::cout<<x1<<"/"<<y1<<"="<<Div(x1,y1)<<std::endl;
    }
catch(...)//Catch any type of exception
    {
try
        {
            std::cout<<" Any type of exception! "<<std::endl;
throw;//Throws the currently handled exception information to the upper catch
        }
catch(int)//Exception types
        {
            std::cout<<" Dividing by 0, Calculation error! "<<std::endl;//Exception handling statement
        }
catch(double)//Exception types
        {
            std::cout<<" Dividing by 0.0, Calculation error! "<<std::endl;//Exception handling statement
        }

    }

return0;
}

Results:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201308/2013082009365514.jpg ">


Related articles: