C++中的函数异常声明

首先来看一段代码:

#include <iostream>
#include <string>

using namespace std;

int func(int i, int j) throw(int, char)
{
    if( (0 < j) && (j < 10) )
    {
        return (i + j);
    }
    else
    {
        throw '0';
    }
}

void test(int i) try
{
    cout << "func(i, i) = " << func(i, i) << endl;
}
catch(int j)
{
    cout << "Exception: " << j << endl;
}
catch(...)
{
    cout << "Exception..." << endl;
}

int main(int argc, char *argv[])
{
    test(5);
    
    test(10);
    
    return 0;
}

请问这段代码 void test(int i)in func(int i, int j) 在定义时,比较诡异的写法是什么意思呢? 为什么会在 int func(int i, int j) 后面跟个 throw(int, char) ,而在 void test(int i) 后面跟着 try ... catch... 语句块呢?

其实这里有一个新的知识点: 函数异常声明

  • try ... catch ... 用于分隔正常功能代码和异常处理代码
  • try ... catch ... 可以直接将函数实现分隔为2部分
  • 函数声明和定义时可以直接指定可能抛出的异常类型
  • 异常声明称为函数的一部分可以提高代码可读性

所以在上述那段代码里:

int func(int i, int j) throw(int, char)
{
    if( (0 < j) && (j < 10) )
    {
        return (i + j);
    }
    else
    {
        throw '0';
    }
}

int func()函数 后面指定了可能抛出的异常类型为 int 和 char 类型,也就是说func函数体在执行过程中可能会抛出int类型或者char类型的异常。

void test(int i) try
{
    cout << "func(i, i) = " << func(i, i) << endl;
}
catch(int j)
{
    cout << "Exception: " << j << endl;
}
catch(...)
{
    cout << "Exception..." << endl;
}

而在 test()函数中,使用了try ... catch ...语句块把正常代码和异常代码分隔开,当正常代码在执行过程中,无法继续往下执行,就会抛出事先声明好的异常,然后 catch语句块中进行捕获。而catch语句块已经事先声明好数据类型,所以捕获异常数据时,根据异常数据类型来判断执行那段catch语句,如果没有匹配上,就会执行参数为 ...的catch语句,它代码任意类型。

由于这里抛出了 char类型 的 '0',所以会执行最后一个catch语句块。

最后给出上述代码的执行结果:

func(i, i) = 10
func(i, i) = Exception...

接下来给出几个注意事项:

  • 函数异常声明时一种与编译器之间的契约
  • 函数声明异常后就只能抛出声明的异常
    • 抛出其它异常将导致程序运行终止
    • 可以直接通过异常声明定义无异常函数
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容