c++那些事儿8 0 异常

235 阅读2分钟

###知识点综述:


C++异常:指程序在执行过程中出现的意外情况,异常通常会使程序的正常流程被打断。
		异常提供了一种转移程序控制权的方式。
		C++ 异常处理涉及到三个关键字:try、catch、throw。

try,catch,throw:
    try 块中的代码标识将被激活的特定异常。它后面通常跟着一个或多个 catch 块。
	catch: 在您想要处理问题的地方,通过异常处理程序捕获异常。catch 关键字用于捕获异常。
	throw: 当问题出现时,程序会抛出一个异常。这是通过使用 throw 关键字来完成的。
格式:
      try{
          // 出现问题的code
      }catch( Exception e ){
          // 处理异常的代码
       }

 如果您想让 catch 块能够处理 try 块抛出的任何类型的异常,则必须在异常声明的括号内使用省略号 ...
    try{
          // 出现问题的code
      }catch(.... ){
          // 处理异常的代码
       }


**除法中,除数为0的 vs出现的异常。**

异常1.PNG
###C++异常类图如下:

c++异常类图.PNG

###异常相关的代码:


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

//继承c++异常父类 exception
class OperatorTypeException:public exception {
	string message;
public:
	OperatorTypeException(string message="发生异常,运算符错误。") {
		this->message = message;
	}
	void what() {
	cerr<<message;
	}

};
//c++异常类相比java少了许多,可以继承exception, 也可以不继承。
class Calacute {
private:
	int num1;
	char oper;
	int num2;
public:
	Calacute(int num1, char oper, int num2);
	int calcu();
};

Calacute::Calacute(int num1, char oper, int num2) {
	this->num1 = num1;
	this->oper = oper;
	this->num2 = num2;
}

int  Calacute::calcu() {
		switch (oper) {
		case '+':
			return num1 + num2; break;
		case '-':
			return num1 - num2; break;
		case '*':
			return num1 * num2; break;
		case '/':
			if (num2 == 0)
				throw - 1; //除数为0异常抛出
			return  num1 / num2; break;
		default:
			throw OperatorTypeException (); //自定义的异常 抛出。

		            }

	}


int main() {

	int num1;
	int num2;
	char oper;
	try {
		cout << "put into num1=";
		cin >> num1;
		cout << "put into operator:";
	    cin >> oper;
		cout << "put into num2=";
		cin >> num2;
		Calacute cau(num1, oper, num2);
		int end= cau.calcu();
		cout << "num1"<<oper<<"num2=" <<end << endl;
	}

	catch (OperatorTypeException  &e) {
		e.what();
	}
	catch (int) {
		cerr << "发生,异常除数为0" << endl;
	}
	

	system("pause");
	return 0;
}

###异常捕获后的结果如下:
![运算符错误.PNG](http://upload-images.jianshu.io/upload_images/4976516-a9876c1a4fd68574.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

除数为0异常.PNG

程序正常执行.PNG


>**语言的知识点是相通的,java,js,py的异常也是,try,catch,throw等关键字处理的。** ``` 近来身体出现问题,本计划c++写完,在写java相关语法,在........ 所以博客的更新也不定时了。