如果没有try-catch语句,我们的函数可能只能靠返回负数之类的方式来表示出错,但这不是可以依靠的方法,因为很多函数的调用者根本不在意函数的返回值,没有强制的约束让调用者去处理函数发生的错误,而try-catch配上throw的方式则不同,如果用户不处理这些错误, 那么程序可能会死掉。下面就来测试一下C++中的try-catch语句。
首先,try-catch语句是不止可以返回runtime-error,它可以返回任何值,如一个int或string,甚至任何用户自定义类型。
throw一个int:
#include <iostream>
using namespace std;
void test()
{
throw 10;
}
int main()
{
try
{
test();
}
catch(int &a)
{
cout << a << endl;
}
return 0;
}
测试结果为:
我们再定义一个class并让test2函数把它throw出来:
#include <iostream>
using namespace std;
void test()
{
throw 10;
}
class A
{
public:
const char *a = "class";
};
int test2()
{
A a;
throw a;
}
int main()
{
try
{
test2();
}
catch(int &a)
{
cout << a << endl;
}
catch(A &a)
{
cout << a.a << endl;
}
return 0;
}
下面是测试结果:
可以看到类中的字符串被正确输出了。那么新的疑问来下,catch处理完后会继续执行try中的语句吗?我们在try语句中执行两个函数, 第一个是test函数,第二个是test2函数,我们看下处理完test中的throw后,会不会处理test2。
#include <iostream>
using namespace std;
void test()
{
throw 10;
}
class A
{
public:
const char *a = "class";
};
int test2()
{
A a;
throw a;
}
int main()
{
try
{
test();
test2();
}
catch(int &a)
{
cout << a << endl;
}
catch(A &a)
{
cout << a.a << endl;
}
cout << "end" << endl;
return 0;
}
结果如下:
如我们所见只输出了一个10,即catch执行完后不会继续执行try中的语句,而是直接执行catch之后的cout。
最后,细心的朋友可能发现了,我们一直是用引用来接收throw出来的值的,这样合法么?从上面的结果看来,是合法的,我们接收到的值并输出了它们。但对于一般的return语句来说,这是不合法的,我们看下面的例子:
#include <iostream>
using namespace std;
int test3()
{
return 10;
}
int main()
{
int &b = test3();
cout << b << endl;
return 0;
}
结果是,无法通过编译,
可见throw和return还是有区别的。可以直接用non-const引用来接收右值。但具体原理不详,如果有知道的大神可以在评论里回复下,或者等我哪天知道了再补。