问题:c++异常处理是不是必须有try,才能有catch?下面自己验证下
方法1:如果没有try? catch语句块能不能处理异常?
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
int i = 0;
//自己试了下,没有try就不能用catch捕捉异常
try{
if(i == 0)
throw runtime_error("zero devide");
}
catch (runtime_error e)
{
cout << e.what() << endl;
}
return 0;
}
在g++下编译结果如下:
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
int i = 0;
//自己试了下,没有try就不能用catch捕捉异常
if(i == 0)
throw runtime_error("zero devide");
//下面会报错的,加上前面的catch语句后就可以正确编译了
catch (runtime_error e)
{
cout << e.what() << endl;
}
return 0;
}
try语句块:跟在try关键字后面的块,以及一个或者多个catch子句,如果try语句块的代码引发异常并且其中一个catch子句匹配该异类型,那么异常被这个catch子句处理。否则,异常将由外围try语句块处理,或者程序终止。
#include <string>
#include <iostream>
#include <stdexcept>
#include <exception>
#include <new>
//#include <type_info>
using namespace std;
void fun1(int a)
{
try {
if(a == 1)
throw bad_alloc();//没有if,throw不执行吗?
}
//catch (bad_alloc e) {cout << "bad_alloc inner" << e.what() <<endl;}
// catch (exception e){cout << "fun1.exception"<< e.what() << endl;}
catch (runtime_error e)
{cout << "fun1::runtime_error" << endl;}
}
void try_fun()
{
int a = 1;
try{
if(a == 0)
throw exception();
if(a == 1)
{
fun1(a);
}
if(a == 2)
throw bad_cast();
}
catch (bad_alloc ){ cout << "try_fun::bad alloc" << endl;}
catch (bad_cast e){cout << e.what() << endl;}
catch (exception e){ cout << e.what() << endl;}
}
int main()
{
try_fun();
return 9;
}
当catch子句的声明类型是基类的引用的时候, 那么可以发生动态绑定的哦,看下面的例子
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;
class A{
public:
A(int aa):a(aa){}
virtual void print()
{
cout << "A's a is: " << a <<endl;
}
private:
int a;
};
class B:public A{
public:
B(int aa,int bb):A(aa),b(bb){}
virtual void print()
{
cout << "B's b is:" << b <<endl;
}
private:
int b;
};
void fun()
{
int a = 1234;
try{
if(a == 1234)
{
B b(111111,222222);
throw b; //派生类对象扔出去
}
}
//catch (A a){ a.print();} //可以捕获类型A或者类型A的继承类B
//catch (B b){ b.print();} //可以捕获B类,但是不能捕获基类
//如果是基类的引用,那么可以捕获它本身类型或者它的基类:
catch(A & a){
cout << "exception declaration type is A:" << endl;
a.print();
}
}
int main()
{
fun();
return 0;
}
下面的运行结果显示,确实是发生了动态绑定。
exception declaration type is A:
B's b is:222222
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)