try throw catch

#include "stdafx.h"

#include <iostream>
#include <stdlib.h>
using namespace std;

//定义一个错误类
class RangeException{
public:
    const char* range_error;
    RangeException(const char* s):range_error(s){}
};

double Fuc(double x, double y){
    if(y == 0){
        throw RangeException("error of dividing zero.
"); //抛出一个错误
    }
    return x/y;
}

void main()
{
    double res;
    try{
        res = Fuc(2,3);
        cout << "The result of x/y is : " << res << endl;
        res = Fuc(4,0);
    }
    catch(RangeException e){    //捕捉到一个错误e
        cerr << e.range_error;
        cin >> res;
        exit(1);
    }
    cin >> res;
}

显示结果:

当抛出的错误类中有构造函数和析构函数的时候会发生下面这样的情况。在下面的代码中,ExceptionClass是一个类,它的构造函数以一个字符串做为参数。也就是说,在throw的时候,C++的编译器先构造一个ExceptionClass的对象,让它作为throw的值抛出去。同时,程序返回,调用析构

#include "stdafx.h"
#include <iostream>
using namespace std;

class ExceptionClass{
    const char* name;
public:
    ExceptionClass(const char* name = "default name"){
            cout << "Construct " << name << endl;
          this->name = name;
    }
    ~ExceptionClass(){
        cout << "Destruct " << name << endl;
    }
    void mythrow(){
        throw ExceptionClass("my throw");
    }
};

void main(){
    ExceptionClass e("Test");
    try{
        e.mythrow();
    } 
    catch(...){
         cout << "*********" << endl;
    }
}

显示的结果是:

Construct Test
Construct my throw
Destruct my throw
****************
Destruct my throw   (这里是异常处理空间中对异常类的拷贝的析构)
Destruct Test

也就是说这里还存在一个对异常类的拷贝操作。

============================================================================================

如果有多个错误类型,那么catch语句可以这样写:

void Func()
{
try
{
    // 这里的程序代码完成真正复杂的计算工作,这些代码在执行过程中
    // 有可能抛出DataType1、DataType2和DataType3类型的异常对象。
}
catch(DataType1& d1)
{
}
catch(DataType2& d2)
{
}
catch(DataType3& d3)
{
}
// 注意上面try block中可能抛出的DataType1、DataType2和DataType3三
// 种类型的异常对象在前面都已经有对应的catch block来处理。但为什么
// 还要在最后再定义一个catch(…) block呢?这就是为了有更好的安全性和
// 可靠性,避免上面的try block抛出了其它未考虑到的异常对象时导致的程
// 序出现意外崩溃的严重后果,而且这在用VC开发的系统上更特别有效,因
// 为catch(…)能捕获系统出现的异常,而系统异常往往令程序员头痛了,现
// 在系统一般都比较复杂,而且由很多人共同开发,一不小心就会导致一个
// 指针变量指向了其它非法区域,结果意外灾难不幸发生了。catch(…)为这种
// 潜在的隐患提供了一种有效的补救措施。
catch(…)
{
}
}

============================================================================================

使用异常规格编程
如果我们调用别人的函数,里面有异常抛出,用去查看它的源代码去看看都有什么异常抛出吗?这样就会很烦琐。比较好的解决办法,是编写带有异常抛出的函数时,采用异常规格说明,使我们看到函数声明就知道有哪些异常出现。

============================================================================================

转:

1. http://blog.sina.com.cn/s/blog_a9303fd901018ost.html

2. http://blog.csdn.net/codestinity/article/details/6877581

原文地址:https://www.cnblogs.com/Key-Ky/p/3535193.html