try-catch的结构为:
try
{
catch(异常信息类型[变量名])
{
说明:
(1)被检测的函数必须放在try块中,否则不起作用。
(2)try块和catch块作为—个整体出现,catch块是try-catch结构中的一部分,必须紧跟在try块之后,不能单独使用,在二者之间也不能插入其他语句。
(3)try和catch块中必须有用花括号括起来的复合语句,即使花括号内只有一个语句,也不能省略花括号。
(4)一个try-catch结构中只能有一个try块,但却可以有多个catch块,以便与不同的异常信息匹配。
(5)catch后面的圆括号中,一般只写异常信息的类型名,如catch(TYPE),catch只检查所捕获异常信息的类型:
(6)如果在catch子句中没有指定异常信息的类型,而用了删节号“…”,则表示它可以捕捉任何类型的异常信息,如:
(7)try-catch结构可以与throw出现在同一个函数中,也可以不在同一函数中。当throw抛出异常信息后,首先在本函数中寻找与之匹配的catch,如果在本函数中无try-catch结构或找不到与之匹配的catch,就转到其上一层去处理,如果其上一层也无try-catch结构或找不到与之匹配的catch,则再转到更上一层的try-catch结构去处理,也就是说转到离开出现异常最近的try-catch结构去处理。(也就是异常处理的嵌套)。
(8)在进行异常处理后,程序并不会自动终止,继续执行catch子句后面的语句。
(9)在某些情况下,在throw语句中可以不包括表达式。
(10)如果throw抛出的异常信息找不到与之匹配的catch块,那么系统就会调用一个系统函数terminate,使程序终止运行。
(11)如果在try块(或try块中调用的函数)中定义了类对象,在建立该对象时要调用构造函数。在执行try块(包括在try块中调用其他函数)的过程中如果发生了异常,此时流程立即离开try块(如果是在try块调用的函数中发生异常,则流程首先离开该函数,回到调用它的try块处,然后流程再从try块中跳出转到catch处理块)。这样流程就有可能离开该对象的作用域而转到其他函数,因而应当事先做好结束对象前的清理工作,C++的异常处理机制会在throw抛出异常信息被catch捕获时,对有关的局部对象进行析构(调用类对象的析构函数),析构对象的顺序与构造的顺序相反,然后执行与异常信息匹配的catch块中的语句。
亲测过的小程序:
NO1:
#include
#include
using
int
{
double
double
cout<<"please
cin>>a>>b>>c;
try
{
while(a>0
{
cout<<triangle(a,b,c)<<endl;
cin>>a>>b>>c;
}
}
catch(double)
{
cout<<"a="<<a<<",b="<<b<<",c="<<c<<",that
}
cout<<"end"<<endl;
return
}
double
{
//double
double
if(a+b<=c||b+c<=a||c+a<=b)
throw
return
}
#include
using
int
{
void
try
{
f1(
}
catch(double)
{
cout<<"OK0!"<<endl;
}
cout<<"end0"<<endl;
return
}
void
{
void
try
{
f2();
}
catch(
{
cout<<"OK1!";
}
cout<<"end1"<<endl;
}
void
{
void
try
{
f3();
}
catch(int)
{
cout<<"Ok2!"<<endl;
}
cout<<"end2"<<endl;
}
void
{
double
try
{
throw
}
catch(float)
{
cout<<"OK3!"<<endl;
}
cout<<"end3"<<endl;
}
运行结果:
OK0
end0。
#include
#include
using
class
{
public:
Student(int
{
cout<<"construtor-"<<n<<endl;
num=n;
name=nam;
}
~Student()
{
cout<<"destructor-"<<num<<endl;
}
void
private:
int
string
};
void
{
if(num==0)
throw
else
cout<<num<<"
cout<<"in
}
void
{
Student
stud1.get_data();
Student
stud2.get_data();
}
int
{
cout<<"main
cout<<"call
try
{
fun();
}
catch(int
{
cout<<"num="<<n<<",error!"<<endl;
}
cout<<"main
return
}
很有意思哟!