/************************************************************************************************ * Name said: Exceptions.cpp * Function: Learning C + + Premier Note Exception handling * Description: Throwing a custom Exception class object throws a built-in type object (such as int) although C + + supports exceptions, the C + + program still tries to use other errors Technology (c + + Premier) * Author: Jarvischu * Time: 2011-7-22 created ****************************************************************
/#include <iostream> #include <string> using namespace std; #define TYPE_CLASS 0//throws an exception for a custom class type Object #define TYPE_INT 1//throws an integer exception #define TYPE_ENUM 2 The exception that throws the enumeration #define TYPE_FLOAT 3//Throw FLOAT exception #define TYPE_DOUBLE 4//Throw DOUBLE exception typedef int TYP E
The type of the exception enum Week{monday,tuesday,wednesday,thursday,friday,saturday,sunday};
Custom exception Class class myexception{Public:myexception (String msg) {err_msg = msg;}
void Showerrormsg () {Cerr<<err_msg<<endl;} ~myexception () {} private:string err_msg;
}; The function that throws the exception//Where throw (Myexception,int,week) is called an exception specification,//It tells the compiler that the function does not throw other types of exception//exception specifications that can not be written, and that defaults can throw any type of exception//
If an exception we do not capture, it will be terminate handled by the system call. If an exception type is not written to the exception specification, we cannot catch it using catch, which is captured by the system, calling terminate void Kindsofexception (type type) throw (Myexception,int,week, float,double) {switch (type) {case Type_class:throw myexception ("exception! Type of Class ");
Class break; Case Type_int:throw 2011;
Integral type break; Case Type_enum:throw Monday;
Enumerate the break; Case Type_float:throw 1.23f;
float break; Case Type_double:throw 1.23;
Double break;
Default:break;
int main () {int type;
cout<< "Input" type (0,1,2,3,4): ";
cin>>type;
try{kindsofexception (type); catch (MyException e) {//If we use the throw exception specification, but did not write myexception to the throw columnTable, e.showerrormsg ();
The myexception exception is not captured here, and is processed by the system call terminate.
catch (float f) {cerr<< "float" <<f<<endl;
catch (double D) {cerr<< "double" <<d<<endl; catch (int i) {cerr<< "exception!
Type of Int--> "<<i<<endl; catch (Week Week) {cerr<< exception!
Type of Enum--> "<<week<<endl;
//can have more catch statements return 0;
}