C++处理异常程序小例子

>>>>所有代码都是在win10+vs2017上运行<<<<

1、处理除数为0

#include "pch.h"
#include<cstdlib> #include<iostream> #include<string> using namespace std; class Error { public: virtual void showErrorMsg() = 0; }; class MyExecptionForZero : public Error { private: string errMsg; public: MyExecptionForZero(string str) : errMsg(str) {}; void showErrorMsg() { cout << errMsg << endl; } }; void myTeset(int i, int j) { MyExecptionForZero m("除数为0啦"); cout << "I want to get the result for j/i ..." << endl; if (i == 0) { throw m; } else { cout << j / i << endl; } } int main(int argc, char *argv[]) { int i = 0; int j = 4; try { myTeset(i, j); } catch (Error &e) { e.showErrorMsg(); } system("PAUSE"); return EXIT_SUCCESS; }

2、访问数组越界

#include "pch.h"
#include<iostream>
using namespace std;
enum index { underflow, overflow };
int array_index(int *a, int n, int index);

class error {
	virtual void showerrormsg() = 0;
};

int main()
{
	int *a = new int[10];
	for (int i = 0; i < 10; i++)
		a[i] = i;

	cout << a[100] << endl;
	try
	{
		cout << a[100] << endl;
		cout << array_index(a, 10, 5) << endl;
		cout << array_index(a, 10, -1) << endl;
		cout << array_index(a, 10, 15) << endl;
	}
	catch (index e)
	{
		if (e == underflow)
		{
			cout << "index underflow!" << endl;
			exit(-1);
		}
		if (e == overflow)
		{
			cout << "index overflow!" << endl;
			exit(-1);
		}
	}
	return 0;
}
int array_index(int *a, int n, int index)
{
	if (index < 0) throw underflow;
	if (index > n - 1) throw overflow;
	return a[index];
}

  

猜你喜欢

转载自www.cnblogs.com/qiang-upc/p/12197229.html