一句话总结:使用得当,如虎添翼;处处滥用,养虎为患。
1、自定义抛出异常
#include <iostream>
#include "CRTTI.hpp"
#include <time.h>
using namespace std;
int testException()
{
//throw 1.0;
//throw 1;
string str1("kkk");
throw str1;
return 1;
}
int main(int argc, const char * argv[]) {
// insert code here...
clock_t startTime = clock();
cout<<"test exception"<<endl;
try {
testException();
} catch (int) {
cout<<"catch int exception"<<endl;
} catch (double i ) {
cout<<"catch double exception: "<<i<<endl;
} catch(string str) {
cout<<"catch string exception: "<<str<<endl;
} catch(char *str) {
cout<<"catch char* exception: "<<str<<endl;
} catch (...) {
cout<<"unknown exception"<<endl;
}
clock_t endTime = clock();
cout<<"cost time: "<<(endTime-startTime)*1.0/CLOCKS_PER_SEC<<endl;
return 0;
}
2、继承异常类
class CMyException : public exception
{
virtual const char* what() const throw()//后面的const throw()不是函数,这个东西叫异常规格说明,
//表示what函数可以抛出异常的类型,类型说明放到()里,如throw(int),这里面没有类型,就是声明这个函数不抛出异常,
//如果去掉后面的const throw()表示可以抛出任何异常,如virtual const char* what()
{
return "My exception happened";
}
}myException;
int main(int argc, const char * argv[]) {
// insert code here...
try {
if (true) {
throw myException;
}
} catch (exception &e) {
cout<<e.what()<<endl;
}
clock_t startTime = clock();
clock_t endTime = clock();
cout<<"cost time: "<<(endTime-startTime)*1.0/CLOCKS_PER_SEC<<endl;
return 0;
}
3、标准异常
int main(int argc, const char * argv[]) {
// insert code here...
try {
int* a = new int[1000000000000000];
} catch (exception &e) {
cout<<e.what()<<endl;
}
return 0;
}
输出信息:
CppProduct(44654,0x100085000) malloc: *** mach_vm_map(size=4000000000000000) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
std::bad_alloc
Program ended with exit code: 0
不catch异常,就不会出现std::bad_alloc