标准库中提供了很多异常类,他们通过类继承组织起来
// c++标准异常.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<stdexcept>
using namespace std;
class Person {
public:
int age;
Person() {
age = 0;
}
void setAge(int age)
{
if (age < 0 || age>100)
{
throw out_of_range("年龄在0-100才行");
}
this->age = age;
}
};
void test01()
{
Person p;
try{
p.setAge(1000);
}
/*catch (out_of_range e)
{//e.what()是char*
cout << e.what() << endl;
}*/
catch (exception e)
{
cout << e.what() << endl;
}
}
class MyOutOfRange :public exception {
public:
char *sError;
MyOutOfRange(const char * str)
{
sError = new char[strlen(str) + 1];
strcpy_s(sError, 20, str);
}
~MyOutOfRange()
{
if (sError != NULL)
{
delete[] sError;
}
}
virtual const char * what() const {
return sError;
}
};
void fun()
{
throw MyOutOfRange("自己的out_of_range");
}
void test2()
{
try {
fun();
}
catch (exception& e)//抛过来对象,这里没有拷贝构造,所以用引用接
{
cout << e.what() << endl;
}
}
int main()
{
// test01();
test2();
return 0;
}
自己编写异常类
1.建议自己编写的异常类要继承标准异常类,防止混乱
2.继承标准异常类时,应该重载父类的what函数和虚析函数
3.因为栈展开的过程中,要复制异常类型,那么要根据在类中添加的成员考虑是否提供自己的复制构造函数
// c++标准异常.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<stdexcept>
using namespace std;
class BassException {
public:
virtual void what() = 0;
virtual ~BassException() {
}
};
class TargetSpaceNullException :public BassException
{
public:
TargetSpaceNullException()
{
}
virtual void what()
{
cout << "目标空间为空" << endl;
}
~TargetSpaceNullException()
{
}
private:
};
class SourceSpaceNullException :public BassException
{
public:
SourceSpaceNullException()
{
}
virtual void what()
{
cout << "原空间为空"<<endl;
}
~SourceSpaceNullException()
{
}
};
void copy_str(char * target, const char* source)
{
if (target == NULL)
{
//cout << "目标空间为空";
throw TargetSpaceNullException();
}
if (source == NULL)
{
//cout << "原空间为空" << endl;
throw SourceSpaceNullException();
}
int len = strlen(source);
while (*source !='\0')
{
*target = *source;
target++;
source++;
}
}
int main()
{
const char * source = "ddd";
char buf[1024] = { 0 };
//copy_str(buf, source);
//cout << buf << endl;
try {
copy_str(NULL, source);
}
catch (BassException& e)
{
e.what();
}
cout << buf << endl;
return 0;
}