我对你的想法,应该有一个合理的例外如何工作。在本课中,我们将覆盖更多的有趣的一些异常情况。
uncaught例外
在过去的几个实例,有一些真正的功能,其存在的情况下(或另一个函数在某点上的手柄,将调用栈)的异常。在下面的例子,有人会把你mysqrt()抛出的异常,这是什么,但如果真的发生了,没人看?
这是我们的平方根程序,再减去在try块,main():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include "math.h" // for sqrt() function
using
namespace
std;
// A modular square root function
double
MySqrt(
double
dX)
{
// If the user entered a negative number, this is an error condition
if
(dX < 0.0)
throw
"Can not take sqrt of negative number"
;
// throw exception of type char*
return
sqrt
(dX);
}
int
main()
{
cout <<
"Enter a number: "
;
double
dX;
cin >> dX;
// Look ma, no exception handler!
cout <<
"The sqrt of "
<< dX <<
" is "
<< MySqrt(dX) << endl;
}
|
现在,让我们说,用户输入的4,和mysqrt(- 4)提出了一个例外。mysqrt()不处理异常,所以程序堆栈的减少及控制返回到main()。但没有异常处理程序,在这里,所以main()终止。在这一点上,我们就终止了我们的应用!
当main()终止与未处理的异常,操作系统会通知你,已发生未处理的异常错误。它是如何依赖于操作系统,但可能包括打印一个错误信息,弹出错误对话框,或简单的崩溃。这通常是你想要完全避免!抓住所有处理程序
现在,我们发现自己在一个condundrum:函数可以把任何数据类型的例外,如果没有捕获到异常,它会传播到你的程序的顶部,使其终止。
现在,我们发现自己在一个condundrum:函数可以把任何数据类型的例外,如果没有捕获到异常,它会传播到你的程序的顶部,使其终止。因为不知道如何调用功能,甚至实现它是可能的,我们如何才能避免这种情况的发生?
幸运的是,C + +为我们提供了一个机制来捕获所有异常类型。这是被称为一个包罗万象的处理程序。一个捕获所有处理器的工作就像一个正常的CATCH块,除了可以用一种特定类型的捕捉,利用椭圆算子(……)作为型抓。如果你记得的教训7.14,椭圆和为什么要避开他们,椭圆以前用来传递任何类型的一个函数的参数。在这种情况下,他们所代表的任何数据类型的例外。这是一个简单的例子:
2
3
4
5
6
7
8
9
10
11
12
|
try
{
throw
5;
// throw an int exception
}
catch
(
double
dX)
{
cout <<
"We caught an exception of type double: "
<< dX << endl;
}
catch
(...)
// catch-all handler
{
cout <<
"We caught an exception of an undetermined type"
<< endl;
}
|
2
3
4
5
6
7
8
9
10
11
12
|
try
{
throw
5;
// throw an int exception
}
catch
(
double
dX)
{
cout <<
"We caught an exception of type double: "
<< dX << endl;
}
catch
(...)
// catch-all handler
{
cout <<
"We caught an exception of an undetermined type"
<< endl;
}
|