编写自己的异常类
自己的异常类 需要继承于 exception
重写 虚析构 what()
内部维护以错误信息 字符串
构造时候传入 错误信息字符串,what返回这个字符串
string 转 char * .c_str();
main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include <string>
class MyOutOfRangeException:public exception
{
public:
MyOutOfRangeException(string errorInfo)
{
this->m_ErrorInfo = errorInfo;
}
//Exception基类的虚函数
virtual ~MyOutOfRangeException( )
{
}
//Exception基类的虚函数,需要实现
virtual const char * what() const
{
//返回 错误信息
//string 转 char * .c_str()
return this->m_ErrorInfo.c_str();
}
string m_ErrorInfo;
};
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
//年龄做检测
if (age < 0 || age > 200)
{
throw MyOutOfRangeException( string("我自己的年龄越界异常"));
}
}
string m_Name;
int m_Age;
};
void test01()
{
try
{
Person p("张三", 300);
}
catch ( MyOutOfRangeException & e )
{
cout << e.what() << endl;
}
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
本文介绍如何在C++中创建自定义异常类,通过继承exception基类并重写what()函数来实现。示例代码展示了如何在Person类的构造函数中使用自定义异常MyOutOfRangeException进行年龄范围检查。
434

被折叠的 条评论
为什么被折叠?



