zoukankan      html  css  js  c++  java
  • C++异常说明

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

    异常说明也叫作异常类型列表,声明了一个函数可以抛出的异常类型。没有定义异常类型列表的函数可以抛出任意类型的异常,这样看起来比较方便,但是这样的代码是不健壮的,并不是一个良好的编程习惯。函数应告诉程序员它可以抛出哪些异常,由此程序员才能写出健壮的代码,在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;
    }
  • 相关阅读:
    emacs 集成astyle
    git reflog
    rpm 打包的时候 不进行strip
    gmock
    如何对正在运行的进程,进行heap profile
    linux性能压测工具
    默认宏定义
    gdb fabs错误输出
    基于Clang的缓存型C++编译器Zapcc
    grep 多行 正则匹配
  • 原文地址:https://www.cnblogs.com/bwjblogs/p/12826774.html
Copyright © 2011-2022 走看看