< />

C++异常机制 kisara

C++异常机制

class bad_hmean {
private:
    double v1;
    double v2;
public:
    explicit bad_hmean(double a=0, double b=0):v1(a),v2(b){}
    void mesg();
};
inline void bad_hmean::mesg(){
    std::cout<<"heman a=-b"<<v1<<" "<<v2<<std::endl;
}	
class bad_gmean {
public:
    double v1;
    double v2;
    bad_gmean(double a=0, double b=0);
    void mesg();
};
inline void bad_gmean::mesg(){
    std::cout<<"geman argumengs should >=0 "<<v1<<" "<<v2<<std::endl;
}
inline bad_gmean::bad_gmean(double a , double b){
    v1=a,v2=b;
}
#include <iostream>
#include "bad_hmean.h"
#include "bad_gmean.h"
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
double hmean(double a, double b){
    if (a==-b){
        throw bad_hmean(a,b);
    }
    return 2.0*a*b/(a+b);
}
double gmean(double a , double b){
    if (a<0||b<0){
        throw bad_gmean(a,b);
    }
    return std::sqrt(a*b);
}
int main() {
    double x,y,z;
    std::cout<<"Enter two numbers: ";
    while (std::cin>>x>>y){
        try {
            z=hmean(x,y);
            gmean(x,y);
        }catch (bad_hmean &bg){
            bg.mesg();
            cout<<"try again\n";
        }catch (bad_gmean & bg){
            bg.mesg();
        }catch (...){//万能捕捉

        }
        cout<<"Harmonic mean of"<<x<<" and "<<y
        <<" is "<<z<<std::endl;
        cout<<"next : ";
    }
    cout<<"bye\n";
    return 0;
}

在try块中如果没有异常则会跳过catch,否则的话会throw出一些东西,这些东西可以是类可以是字符串,什么都可以,当某个catch的参数与之匹配时就会进入到catch中,示例中我们抛出自定义类,c++为我们准备了很多exception类在相应头文件中。

kisarawechat kisaraalipay