异常
int ret = 0;
try
{
//throw 1;
//throw 'A';
throw 2.14f;
}
catch(int e)
{
cout << "int异常值为: " << e << endl;
}
catch(char e)
{
cout << "char异常值为: " << e << endl;
}
catch(...) //捕获所有异常
{
cout << "其他异常值为: " << endl;
}
栈解旋
异常被抛出后,从进入try块起,到异常被抛掷前,这期间在栈上构造的所有对象,都会被自动析构。析构的顺序与构造的顺序相反,这—过程称为栈的解旋.
try
{
Data ob1;
Data ob2;
Data ob3;
throw 1; //抛出异常后 ob3 ob2 ob1 依次自动释放(栈解旋)
}
catch(int e)
{
cout << "int异常值为: " << e << endl;
}
catch(char e)
{
cout << "char异常值为: " << e << endl;
}
catch(...)
{
cout << "其他异常值为: " << endl;
}
先释放对象再捕获异常
异常的接口声明
异常的接口声明: 可以抛出哪些类型的异常
函数默认 可以抛出任何类型的异常(推荐)
void fun()
{
throw 1; //ok
throw '1'; //ok
throw "hello"; //ok
只抛出特定类型的异常
void fun02() throw(int, char)
{
throw 1; //ok
throw '1'; //ok
throw "hello"; //抛出 不能捕获
}
不能抛出任何异常
void fun03() throw()
{
throw 1; //不能抛出
throw 'o'; //不能抛出
throw "dfj"; //不能抛出
}
异常变量的生命周期
以普通对象接异常值
以对象指针 接异常值
try
{
throw new MyException;
}
catch(MyException *e) //指针对象接异常(delete释放)
{
cout << "普通对象接异常" << endl;
delete e;
}
对象引用接异常值(推荐)
try
{
throw MyException();
}
catch(MyException &e)
{
cout << "普通对象接异常" << endl;
}
异常的多态
//异常基类
class BaseException
{
public:
virtual void printError(){};
};
//空指针异常
class NullPointerException: public BaseException
{
public:
virtual void printError()
{
cout << "空指针异常!" << endl;
}
};
//越界异常
class OutOfRangException: public BaseException
{
public:
virtual void printError()
{
cout << "越界异常!" << endl;
}
};
void doWork()
{
//throw NullPointerException();
throw OutOfRangeException();
}
int main()
{
try
{
doWork();
}
catch(BaseException& ex) //父类引用 可以捕获搭配该父类派生出的所有子类的子类
{
ex.printError();
}
}
C++标准异常
try
{
throw out_of_range("哈哈, 我越界了");
//throw bad_alloc();
}
catch(exception &e)
{
//what()存放的是异常信息(char *方式存在)
cout << e.what() << endl;
}
编写自己的异常
基于标准异常基类 编写自己的异常类
#include <iostream>
using namespace std;
class NewException: public exception
{
private:
string msg;
public:
NewException(){}
NewException(string msg)
{
this->msg = msg;
}
//重写父类的what
virtual const char* what() const throw() //防止父类在子类前抛出标准异常
{
//将string转换成char*
return this->msg.c_str();
}
~NewException(){}
};
int main()
{
try
{
throw NewException("哈哈, 自定义异常");
}
catch(exception &e)
{
cout << e.what() << endl;
}
return 0;
}
标签:20,cout,抛出,try,catch,异常,throw
From: https://www.cnblogs.com/mzx233/p/17765627.html