异常处理

异常处理的思想与程序实现

异常处理的基本思想

异常处理的语法

例12-1处理除零异常

//12_1.cpp
#include <iostream>
using namespace std;
int divide(int x, int y) {
    if (y == 0)
        throw x;
    return x / y;
}
int main() {
    try {
        cout << "5 / 2 = " << divide(5, 2) << endl;
        cout << "8 / 0 = " << divide(8, 0) << endl;
        cout << "7 / 1 = " << divide(7, 1) << endl;
    } catch (int e) {
        cout << e << " is divided by zero!" << endl;
    }
    cout << "That is ok." << endl;
    return 0;
}

异常接口声明

  • 一个函数显式声明可能抛出的异常,有利于函数的调用者为异常处理做好准备
  • 可以在函数的声明中列出这个函数可能抛掷的所有异常类型。

    例如:void fun() throw(A,B,C,D);
    
  • 若无异常接口声明,则此函数可以抛掷任何类型的异常。

  • 不抛掷任何类型异常的函数声明如下:

    void fun() throw();

异常处理中的构造与析构

自动的析构

  • 找到一个匹配的catch异常处理后
    • 初始化异常参数。
    • 将从对应的try块开始到异常被抛掷处之间构造(且尚未析构)的所有自动对象进行析构。
  • 从最后一个catch处理之后开始恢复执行。

例12-2 带析构语义的类的C++异常处理

//12_2.cpp
#include <iostream>
#include <string>
using namespace std;
class MyException {
public:
    MyException(const string &message) : message(message) {}
    ~MyException() {}
    const string &getMessage() const { return message; }
private:
    string message;
};

class Demo {
public:
    Demo() { cout << "Constructor of Demo" << endl; }
    ~Demo() { cout << "Destructor of Demo" << endl; }
};
void func() throw (MyException) {
    Demo d;
    cout << "Throw MyException in func()" << endl;
    throw MyException("exception thrown by func()");
}

int main() {
    cout << "In main function" << endl;
    try {
        func();
    } catch (MyException& e) {
        cout << "Caught an exception: " << e.getMessage() << endl;
    } 
    cout << "Resume the execution of main()" << endl;
    return 0;
}
运行结果:
In main function
Constructor of Demo
Throw MyException in func()
Destructor of Demo
Caught an exception: exception thrown by func()
Resume the execution of main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值