//带析构语义的类c++异常处理 12-2#include<iostream>#include<string>usingnamespace std;classMyException{public:MyException(const string &message):message(message){}~MyException(){}const string &getMessage()const{return message;}private:
string message;};classDemo{public:Demo(){cout <<"Constructor of Demo"<< endl;}~Demo(){cout <<"Destructor of Demo"<< endl;}};voidfunc()throw(MyException){
Demo d;
cout <<"Throw MyException in func()"<< endl;throwMyException("exception thrown by func()");}intmain(){
cout <<"In main function"<< endl;try{func();}catch(MyException& e){
cout <<"Caught an exception: "<< e.getMessage()<< endl;}return0;}
#include<iostream>#include<cmath>usingnamespace std;//给出三角形三边长,计算三角形面积doublearea(double a,double b,double c)throw(invalid_argument){//判断三角形边长是否为正if(a <=0|| b <=0|| c <=0)throwinvalid_argument("the side length should be positive");//判断三边长是否满足三角不等式if(a+b <= c || b+c <= a || c+a <= b)throwinvalid_argument("the side length should fit the triangle inequation ");//由Heron公式计算三角形面积double s =(a+b+c)/2;returnsqrt(s *(s - a)*(s - b)*(s - c));}intmain(){double a,b,c;//三角形三边长
cout <<"Please input the side lengths of a triangle:";
cin >> a >> b >> c;try{double s =area(a,b,c);//尝试计算三角形面积
cout <<"Area: "<< s << endl;}catch(exception &e){
cout <<"Error: "<< e.what()<< endl;}return0;}