1- 在函数签名后使用throw(type-list) 是为了让您或将阅读您的代码的程序员知道该函数只能抛出您在@987654323 中指定的类型@。
void f()throw(){};// This function can not throw any object of any type.
void f()throw(A){}; // you can throw any A object +
// any object of a type drived from A if A is a User-defined Type
如果你抛出一个不在异常规范中的类型的对象,std::unexpected() 函数将被调用。
2-这里没有catch块。函数签名后的throw(type-list) 只是为了确保该函数不会抛出除type-list 中类型的对象之外的任何类型。
您使用的称为异常规范,它的一个使用示例如下:
int f(int x)throw(int){
if (x==0) throw 0;
return x;
}
int main(){
try{
f(0);
}
catch(int e){
// something
}
}
你可以记住两件事:
i) 不要使用异常规范,因为它们已被弃用。
ii) 如果您必须使用它们,那么您现在必须使用某些编译器拒绝内联一个函数,因为它有一个异常规范。
更新:
void f()throw(int){
try{
// code goes here ...
throw 1.1; // note this is throwing a float
}
catch(float){
// exception handled
}
}
在这个例子中你不会得到任何错误,即使你抛出一个float类型的异常,这在函数异常规范中没有指定,它只允许你抛出int类型的对象。这是因为您在函数内部处理了异常。
void f()throw(int){
throw 1;
}
int main(){
try{
f();
}
catch(int){// exception handled}
}
您应该始终将您认为可能会引发异常的函数放在try-block 中,因为f() 引发int 并得到处理,所以上面的代码将被正常执行。
void f()throw(int){
throw 1.1; // note this is throwing a float
}
int main(){
try{
f();
}
catch(...){//}
}
这将导致函数调用std::unexpected(),因为您的函数f() 抛出了一个不在函数异常规范中的float 类型的异常。