网站建设 优惠,wordpress批量发布,男女做羞羞的事情网站,花卉网站建设的总结与throw 是C中的关键字#xff0c;用来抛出异常。如果不使用 throw 关键字#xff0c;try 就什么也捕获不到#xff1b;上节提到的 at() 函数在内部也使用了 throw 关键字来抛出异常。throw 既可以用在标准库中#xff0c;也可以用在自定义的函数中#xff0c;抛出我们期望的…throw 是C中的关键字用来抛出异常。如果不使用 throw 关键字try 就什么也捕获不到上节提到的 at() 函数在内部也使用了 throw 关键字来抛出异常。throw 既可以用在标准库中也可以用在自定义的函数中抛出我们期望的异常。throw 关键字语法为 throw exceptionData;
exceptionData 是“异常数据”的意思它既可以是一个普通变量也可以是一个对象只要能在 catch 中匹配就可以。下面的例子演示了如何使用 throw 关键字 #include iostream#include stringusing namespace std;char get_char(const string , int);int main(){ string str c plus plus; try{ coutget_char(str, 2)endl; coutget_char(str, 100)endl; }catch(int e){ if(e1){ coutIndex underflow!endl; }else if(e2){ coutIndex overflow!endl; } } return 0;}char get_char(const string str, int index){ int len str.length(); if(index 0) throw 1; if(index len) throw 2; return str[index];} 运行结果pIndex 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 都能捕获到。更改上例中的代码 #include iostream#include stringusing namespace std;char get_char(const string , int) throw(char, exception);int main(){ string str c plus plus; try{ coutget_char(str, 2)endl; coutget_char(str, 100)endl; }catch(int e){ if(e1){ coutIndex underflow!endl; }else if(e2){ coutIndex overflow!endl; } } return 0;}char get_char(const string str, int index) throw(char, exception){ int len str.length(); if(index 0) throw 1; if(index len) throw 2; return str[index];} 在使用 GCC 的 IDE 中运行代码执行到第 12 行时程序会崩溃。虽然 func 函数检测到下标越界知道发生了异常但是由于 throw 限制了函数只能抛出 char、exception 类型的异常所以 try 将捕获不到异常只能交给系统处理终止程序。需要说明的是C标准已经不建议这样使用 throw 关键字了因为各个编译器对 throw 的支持不同有的直接忽略不接受 throw 的限制有的将 throw 作为函数签名导致引用函数时可能会有问题。上面的代码在 GCC 下运行时会崩溃在 VS 下运行时则直接忽略 throw 关键字对异常类型的限制try 可以正常捕获到 get_char() 抛出的异常程序并不会崩溃。