看个例子:
int foo(int a,int b){
return a/b;
}
void test(){
int a=0;
int b=10;
foo(a,b);
}
此时test函数调用foo函数出现 “除0溢出” 此时出现异常,此时程序调用terminate函数中断程序;
为了避免程序崩溃,会选择抛出异常:
int foo(int a,int b){
if(b==0){
throw 1; //此时throw表示抛出异常,抛出的类型可以是其他数据类型
}
return a/b;
}
void test(){
int a=0;
int b=10;
try{ //尝试运行foo函数,不抛出异常的时候运行
foo(a,b);
}
catch(int){ //catch表示捕获异常,如果抛出的异常为int类型,则运行此处
//...... //若此时此处为throw,则表示test向调用它的函数抛出此异常
}catch(...){ //...表示其他异常 此时运行此处
}
}
如果有异常抛出,则会释放其中的栈上的数据,如:
int foo(int a,int b){
if(b==0){
int c=10;
int d=20;
throw 1; //此时throw表示抛出异常,抛出的类型可以是其他数据类型
}
return a/b;
}
void test(){
int a=0;
int b=10;
try{ //尝试运行foo函数,不抛出异常的时候运行
foo(a,b);
}
catch(int){ //catch表示捕获异常,如果抛出的异常为int类型,则运行此处
//...... //若此时此处为throw,则表示test向调用它的函数抛出此异常
}catch(...){ //...表示其他异常 此时运行此处
}
}
其中的c和d会在抛出异常之前就被释放,按栈释放顺序释放! (一般称之为栈解旋)