C++之异常处理入门

C++ —异常处理入门

异常处理的思想与程序实现

在这里插入图片描述
异常处理的语法:
在这里插入图片描述
例:处理除以0异常

#include <iostream>
using namespace std;

int divide(int x,int y){
	if(y==0)
		throw x;//抛出什么数据都可以,只要抛出和接受约定好就行 
	return x/y;
}
int main()
{
	try{
		cout<<"5/2="<<divide(5,2)<<endl;
		cout<<"8/0="<<divide(8,0)<<endl;
		cout<<"7/1="<<divide(7,1)<<endl;
	}catch(int e){//捕获异常对象,和抛出的类型一样 
		cout<<e<<" is divided by zero!"<<endl;
	}
	cout<<"That is ok."<<endl;
	return 0;
}

在这里插入图片描述
异常接口声明:
一个函数显式声明可能抛出的异常,有利于函数的调用者为异常处理做好准备,增加程序可读性。
在这里插入图片描述

异常处理中的构造与析构

自动析构:
在这里插入图片描述
例:带析构语义的类的C++异常处理

#include <iostream>
#include <string>
using namespace std;

class MyException{
public:
	MyException(const string &message):message(message){}
	~MyException(){}
	const string &getMessage()const {return message;}
private:
	string message;
};

class Demo{
public:
	Demo(){cout<<"Constructor of Demo"<<endl;}
	~Demo(){cout<<"Destructor of Demo"<<endl;}
};

void func() throw(MyException){
	Demo d;
	cout<<"Throw MyException in func()"<<endl;
	throw MyException("exception thrown by func()");
}
int main()
{
	cout<<"In main function"<<endl;
	try{
		func();//此处Demo的对象d会被异常处理机制析构 
	}catch(MyException &e){
		cout<<"Caught an exception:"<<e.getMessage()<<endl;
	}
	cout<<"Resume the execution of main()"<<endl;
	return 0;
}

在这里插入图片描述

标准程序库异常处理

在这里插入图片描述
在这里插入图片描述
标准异常类的基础:
1、exception:标准程序库异常类的公共基类。
2、logic_error表示可以在程序中被预先检测到的异常。(如果小心地编写程序,这类异常能够避免)
3、runtime_error表示难以被预先检测到的异常
例:计算三角形面积

#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;

double area(double a,double b,double c) throw(invalid_argument){
	if(a<=0||b<=0||c<=0)
		throw invalid_argument("the side length should be positive.");
	//标准异常类,通常用字符串表示异常原因 
	if(a+b<=c||a+c<=b||b+c<=a)
		throw invalid_argument("the side length should fit the triangle inequation");
	double s=(a+b+c)/2;
	return sqrt(s*(s-a)*(s-b)*(s-c));
}
int main()
{
	double a,b,c;
	cout<<"Please input the side lengths of a triangle:";
	cin>>a>>b>>c;
	try{
		double s=area(a,b,c);
		cout<<"Area:"<<s<<endl;
	}catch(exception &e){//exception类是invalid_argument类的父类 
		cout<<"Error:"<<e.what()<<endl;
	}
	return 0;
}

正常情况:
在这里插入图片描述
异常:不全为正数
在这里插入图片描述
异常:无法构成三角形
在这里插入图片描述

发布了30 篇原创文章 · 获赞 33 · 访问量 1268

猜你喜欢

转载自blog.csdn.net/weixin_45949075/article/details/104446395