异常

#include <iostream> 
using namespace std;

double division(int a, int b)
{
	if (b == 0)
	{
		throw "除数为零!";  // 一旦满足出现异常的条件就抛出异常
	}
	return a / b;
}

// 程序的主函数
int main()
{
	int a, b;
	double result;

	printf("请输入被除数:");
	scanf_s("%d", &a);

	printf("请输入除数:");
	scanf_s("%d", &b);

	try
	{
		result = division(a, b);  // try中的代码是受保护的代码块,即是受监视的代码块,一旦出现异常将会被catch住
		cout << "result = " << result << endl;
	}
	catch (const char * msg)  // 将异常信息赋值到msg变量进行输出
	{
		cerr << "异常信息:" << msg << endl;
	}

	system("pause");
	return 0;
}

 运行:

 

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

// 继承 exception 异常类
struct MyException : public exception	
{
	// what() 是 exception 异常类的方法, throw() 是异常规格说明,目的是告诉调用这个方法的人会出现哪些异常,没有参数表示可能出现各种异常
	const char * what() const throw()	
	{
		return "C++ Exception.";
	}
};

int main()
{
	try
	{
		throw MyException();	// 抛出一个异常
	}
	catch (MyException &e)		// e 是 Myexception 自定义异常类的对象,即 exception 异常类的对象,可调用 what() 方法获取异常信息
	{
		cout << "MyException Caught:" << endl;
		cout << e.what() << endl;
	}
	catch (std::exception &e)
	{
		// 除了上面的异常之外的其他的异常
	}

	system("pause");
	return 0;
}

 

 

posted @ 2018-03-02 12:43  半生戎马,共话桑麻、  阅读(137)  评论(0)    收藏  举报
levels of contents