在阅读别人开发的项目中,也许你会经常看到了多处使用异常的代码,也许你也很少遇见使用异常处理的代码。那在什么时候该使用异常,又在什么时候不该使用异常呢?在学习完异常基本概念和语法之后,后面会有讲解。
//1.抛出异常
throw 异常对象
//2.异常捕捉
try{
可能会发生异常的代码
}catch(异常对象){
异常处理代码
}
class Data
{
public:
Data() {}
};
void fun(int n)
{
if(n==0)
throw 0;//抛异常 int异常
if(n==1)
throw "error"; //抛字符串异常
if(n==2)
{
Data data;
throw data;
}
if(n>3)
{
throw 1.0;
}
}
int main()
{
try {
fun(6);//当异常发生fun里面,fun以下代码就不会再执行,调到catch处执行异常处理代码,后继续执行catch以外的代码。当throw抛出异常后,没有catch捕捉,则整个程序会退出,不会执行整个程序的以下代码
cout<<"*************"<<endl;
}catch (int i) {
cout<<i<<endl;
}catch (const char *ptr)
{
cout<<ptr<<endl;
}catch(Data &d)
{
cout<<"data"<<endl;
}catch(...)//抓取 前面异常以外的所有其他异常
{
cout<<"all"<<endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
try {
char* p = new char[0x7fffffff]; //抛出异常
}
catch (exception &e){
cout << e.what() << endl; //捕获异常,然后程序结束
}
return 0;
}
输出结果:
当使用new进行开空间时,申请内存失败,系统就会抛出异常,不用用户自定义异常类型,此时捕获到异常时,就可告诉使用者是哪里的错误,便于修改。
#include <iostream>
#include <exception>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
class FileException :public exception
{
public:
FileException(string msg) {
this->exStr = msg;
}
virtual const char*what() const noexcept//声明这个函数不能再抛异常
{
return this->exStr.c_str();
}
protected:
string exStr;
};
void fun()
{
int fd = ::open("./open.txt",O_RDWR);
if(fd<0)
{
FileException openFail("open fail"); //创建异常对象
throw openFail;//抛异常
}
}
int main( )
{
try {
fun();
} catch (exception &e) {//一般需要使用引用
cout<<e.what()<<endl;
}
cout<<"end"<<endl;
return 0;
}
当文件不存在时,输出结果:
如果在Linux上运行,上述代码需要根据环境修改:
98标准写法
~FileException()throw(){}//必须要
virtual const char*what() const throw()//声明这个函数不能再抛异常
{
return this->exStr.c_str();
}
//编译
g++ main.cpp
2011标准写法
~FileException()noexcept{}//必须要
virtual const char*what() const noexcept//声明这个函数不能再抛异常
{
return this->exStr.c_str();
}
//编译
g++ main.cpp -std=c++11 指定用c++11标准编译
1. 使用异常处理的优点:
2. 使用异常的缺点:
3. 什么时候使用异常?
4. 程序所有的异常都可以catch到吗?
原文:https://www.cnblogs.com/lcgbk/p/13858425.html