C++ throw:抛出自己的异常

本文探讨了在C++中使用`throw`关键字抛出自定义异常的不被建议的用法,即直接抛出异常数据。
摘要由CSDN通过智能技术生成
throw 是C++中的关键字,用来抛出异常。如果不使用 throw 关键字,try 就什么也捕获不到;上节提到的 at() 函数在内部也使用了 throw 关键字来抛出异常。

throw 既可以用在标准库中,也可以用在自定义的函数中,抛出我们期望的异常。throw 关键字语法为:

throw exceptionData;

exceptionData 是“异常数据”的意思,它既可以是一个普通变量,也可以是一个对象,只要能在 catch 中匹配就可以。

下面的例子演示了如何使用 throw 关键字:

    
    
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. char get_char(const string &, int);
  5. int main(){
  6. string str = "c plus plus";
  7. try{
  8. cout<<get_char(str, 2)<<endl;
  9. cout<<get_char(str, 100)<<endl;
  10. }catch(int e){
  11. if(e==1){
  12. cout<<"Index underflow!"<<endl;
  13. }else if(e==2){
  14. cout<<"Index overflow!"<<endl;
  15. }
  16. }
  17. return 0;
  18. }
  19. char get_char(const string &str, int index){
  20. int len = str.length();
  21. if(index < 0)
  22. throw 1;
  23. if(index >= len)
  24. throw 2;
  25. return str[index];
  26. }
运行结果:
p
Index overflow!

在 get_char() 函数中,我们使用了 throw 关键字,如果下标越界,就会抛出一个 int 类型的异常:如果是下溢,异常数据的值为 1;如果是上溢,异常数据的值为 2。在 catch 中,将捕获 int 类型的异常,然后根据异常数据输出不同的提示语。

不被建议的用法

throw 关键字除了可以用在函数体中抛出异常,还可以用在函数头和函数体之间,指明函数能够抛出的异常类型。有些文档中称为异常列表。例如:
double func (char param) throw (int);
这条语句声明了一个名为 func 的函数,它的返回值类型为 double,有一个 char 类型的参数,并且只能抛出 int 类型的异常。如果抛出其他类型的异常,try 将无法捕获,只能终止程序。

如果希望能够抛出多种类型的异常,可以用逗号隔开:
double func (char param) throw (int, char, exception);
如果不希望限制异常类型,那么可以省略:
double func (char param) throw ();
如此,func() 函数可以抛出任何类型的异常,try 都能捕获到。

更改上例中的代码:

    
    
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. char get_char(const string &, int) throw(char, exception);
  5. int main(){
  6. string str = "c plus plus";
  7. try{
  8. cout<<get_char(str, 2)<<endl;
  9. cout<<get_char(str, 100)<<endl;
  10. }catch(int e){
  11. if(e==1){
  12. cout<<"Index underflow!"<<endl;
  13. }else if(e==2){
  14. cout<<"Index overflow!"<<endl;
  15. }
  16. }
  17. return 0;
  18. }
  19. char get_char(const string &str, int index) throw(char, exception){
  20. int len = str.length();
  21. if(index < 0)
  22. throw 1;
  23. if(index >= len)
  24. throw 2;
  25. return str[index];
  26. }
在使用 GCC 的 IDE 中运行代码,执行到第 12 行时程序会崩溃。虽然 func 函数检测到下标越界,知道发生了异常,但是由于 throw 限制了函数只能抛出 char、exception 类型的异常,所以 try 将捕获不到异常,只能交给系统处理,终止程序。

需要说明的是,C++标准已经不建议这样使用 throw 关键字了,因为各个编译器对 throw 的支持不同,有的直接忽略,不接受 throw 的限制,有的将 throw 作为函数签名,导致引用函数时可能会有问题。上面的代码在 GCC 下运行时会崩溃,在 VS 下运行时则直接忽略 throw 关键字对异常类型的限制,try 可以正常捕获到 get_char() 抛出的异常,程序并不会崩溃。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值