欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

异常处理(自定义异常,异常处理类)

程序员文章站 2024-03-20 20:09:22
...

一:自定义异常

#include<iostream>
#include<string>
using namespace std;
//自定义一个异常处理类
class listException {
public:
	listException(string str):str(str){}
	void print();


protected:
	string str;
};
void listException::print()
{
	cout << str << endl;
}
//抛出异常的函数(可能的异常都可以通过函数形式书写来调用)
int result(int a, int b)
{
	if (b == 0)
		throw listException("b==0被除数异常");
	return a / b;
}

int main()
{
	try {
		result(1, 0);
	}
	//捕捉异常
	catch (listException e)
	{
		e.print();
	}
	return 0;
}

二:异常处理类

#include<iostream>
#include<string>
#include<exception>
using namespace std;
//exception 为库中异常类

//class exception
//{
//public:
//
//    exception() noexcept
//        : _Data()
//    {
//    }
//
//    explicit exception(char const* const _Message) noexcept
//        : _Data()
//    {
//        __std_exception_data _InitData = { _Message, true };
//        __std_exception_copy(&_InitData, &_Data);
//    }
//
//    exception(char const* const _Message, int) noexcept
//        : _Data()
//    {
//        _Data._What = _Message;
//    }
//
//    exception(exception const& _Other) noexcept
//        : _Data()
//    {
//        __std_exception_copy(&_Other._Data, &_Data);
//    }
//
//    exception& operator=(exception const& _Other) noexcept
//    {
//        if (this == &_Other)
//        {
//            return *this;
//        }
//
//        __std_exception_destroy(&_Data);
//        __std_exception_copy(&_Other._Data, &_Data);
//        return *this;
//    }
//
//    virtual ~exception() noexcept
//    {
//        __std_exception_destroy(&_Data);
//    }
//
//    _NODISCARD virtual char const* what() const
//    {
//        return _Data._What ? _Data._What : "Unknown exception";
//    }
//
//private:
//
//    __std_exception_data _Data;
//};

//定义一个testException异常继承于库中异常类exception
class testException :public exception {

public:
	testException():exception("Error"){}

};

int main()
{
	
	try {
		if (1)
			throw testException();
	}
	catch (testException e)
	{
		cout << e.what() << endl;
	}
	return 0;
}

C++标准的异常

①bad_alloc	
②bad_cast
③bad_typeid
④bad_exception
⑤logic_error(domain_error,invalid_argument,length_error,out_of_range)
⑥runtime_error(overflow_error,range_error,underflow_error)

①异常可以通过new抛出

try {
		int* p1 = new int[0xfffffff];
		int* p2 = new int[0xfffffff];
	}
	catch(bad_alloc&e){
		cout<<e.what()<<endl;
	}

异常处理(自定义异常,异常处理类)
②异常可通过dynamic_cast抛出
③异常可通过typeid抛出
④异常在处理C++程序中无法预期的异常时非常有用

相关标签: C++自学笔记