首页 > 编程语言 > 详细

C++异常说明

时间:2020-05-06 14:05:54      阅读:51      评论:0      收藏:0      [点我收藏+]

到目前为止,我们定义的函数都是没有异常类型列表的。

异常说明也叫作异常类型列表,声明了一个函数可以抛出的异常类型。没有定义异常类型列表的函数可以抛出任意类型的异常,这样看起来比较方便,但是这样的代码是不健壮的,并不是一个良好的编程习惯。函数应告诉程序员它可以抛出哪些异常,由此程序员才能写出健壮的代码,在try-catch中处理所有可能的异常。

异常说明在函数头声明,语法如下:

returnType functionName(parameterList) throw (exceptionList)

若将throw(),及括号中为空,放置于函数头之后,那么表示这个函数不能够抛出任何的异常。

看一个例子:

#include <iostream>
#include <stdexcept>

using namespace std;

int quotient(int a, int b) throw (runtime_error){
    if (b == 0) {
        throw runtime_error("整数不能除零!");
    }
    return a/b;
}
int main()
{
    cout << "输入两个数:" << endl;
    int a, b;
    cin >> a >> b;
    try{
        cout << a << "/" << b << "=" << quotient(a,b) << endl;
    } catch (runtime_error& e){
        cout << e.what() << endl;
    }

    return 0;
}

 

C++异常说明

原文:https://www.cnblogs.com/bwjblogs/p/12826774.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!