I have never practiced exceptions well before, and I have never had a deep understanding of them. Recently I 've been reading Thinking In C ++, and its first chapter describes a lot of abnormal code. I thought it was very simple, however, after compilation and debugging on the machine, we found that this is not the case. During the execution of the following exception program, I found some special features (maybe the veteran has been familiar with it for a long time) and recorded them for future viewing! The program source code is:
//: C01: Unexpcected. cpp
// Exception specifications & unexcepted (),
// {-Msc} (doesn' t terminate properly)
# Include <exception>
# Include <iostream>
Using namespace std;
Class Up ...{};
Class Fit ...{};
Void g ();
Void f (int I) throw (Up, Fit)
...{
Switch (I)
...{
Case 1: throw Up ();
Case 2: throw Fit ();
}
G ();
}
// Void g () {}// version 1
Void g ()
...{
Throw 32;
}
Void my_unexpected ()
...{
Cout <"unexpected exception thrown" <endl;
Exit (0 );
}
Int main ()
...{
Set_unexpected (my_unexpected); // Ignores return value
For (int I = 1; I <= 3; I ++)
Try
...{
F (I );
}
Catch (Up)
...{
Cout <"Up caught" <endl;
}
Catch (Fit)
...{
Cout <"Fit caught" <endl;
}
Return 0;
}/**////:~
The entire program structure is very simple. The set_unexpected function is a standard function provided in the exception header file. It is used to set that the thrown exception is not listed in the exception specification Description (exception specification) unexpected function called in the exception set (default)
Function f declares the exception type description set, but calls the g Function of version 2. The exception thrown by this function is not in the exception type description set of function f, therefore, the unexpected function is called by default. The my_unexpected function is called here.
Call and run the function in VC to throw an error dialog box:
After debugging the program, I was surprised to find that the program running sequence was
First, execute the for statement, then execute the f function call in the try block, then throw an Up exception, jump to the catch (Up) Statement for execution, output Up caught, jump to the return 0 statement, then execute the for statement, reloop, throw the Fit exception, return 0 and then run the for statement, and throw the Debug Error dialog box!
The execution of abnormal programs was so clever!
As mentioned in the article: embed the try block in the for, while, do, or if block, and trigger an exception to try to solve the problem; then re-test the code in the try block! That is to say, even if one of the execution processes throws an exception, for, while, do, or if can all continue to be executed, it will only affect one of the processes, the global impact is not very great.
This program can be correctly compiled and run in cygwin! It shows that VC does not support Standard C ++ very well!
<