异常使用三部曲:1 框定异常(try语句块)
在祖先函数出,框定可能产生错误的语句序列,它是异常的根据。
2 定义异常处理(catch语句块)
将出现异常后的处理过程放在catch块中,以便当异常被抛出,因类型匹配而捕捉是,就处理异常,而不是延时处理,或者不处理。
3 抛送异常(throw语句)
在可能产生错误的函数中定义,如果有错,就抛出异常。
编程前,设计类,同时设计类可能抛出的有关异常类。编程中,当try执行中又异常抛出,则用catch捕捉异常,并当场处理。
异常类设计:
//MyException.h
#include "stdafx.h"
class MyException
{
public:
virtual const char *what(){ return "To the Base Exception"; }
};
class HardWareError:public MyException
{
public:
virtual const char *what(){ return "To the HardWare Exception"; }
};
class PerformError:public MyException
{
public:
virtual const char *what(){ return "To the Perform Exception"; }
};
class SizeError:public MyException
{
public:
virtual const char *what(){ return "To the Size Exception"; }
};
class HSizeError:public SizeError
{
public:
virtual const char *what(){ return "To the HSize Exception"; }
};
class VSizeError:public SizeError
{
public:
virtual const char *what(){ return "To the VSize Exception"; }
};
class OtherError:public MyException
{
public:
virtual const char *what(){ return "To the Other Exception"; }
};
//exceptionTest.h
#include "stdafx.h"
#include "MyException.h"
class exceptionTest
{
private:
void metalPieseProcess(int);
void metalGroupProcess(int);
void hProcess();
void vProcess();
void PerformTest();
void calcVSize();
bool tooSmallHSize(){return true;}
bool performTeatFail(){return false;}
bool toSmallVSize(){return false;}
public:
exceptionTest(){}
~exceptionTest(){}
void RunTest();
};
//exceptionTest.cpp
#include "stdafx.h"
#include "exceptionTest.h"
#include <exception>
#include <stdexcept>
#include <typeinfo>
using namespace std;
void exceptionTest::RunTest()
{
try
{
for (int i = 0;i < 10; i++)
{metalGroupProcess(i);
}
}
catch (MyException& e)
{
if (e.what() == "To the HardWare Exception")
{cout<<"停机"<<endl;
}
if (e.what() == "To the Perform Exception")
{cout<<"加工件离机,温柔停机"<<endl;
}
if (e.what() == "To the Other Exception")
{cout<<"除暴停机"<<endl;
}
cout<<"Myexception"<<e.what()<<endl;
}catch(exception e)
{
cout<<"StandardException: "<<typeid(e).name()<<endl;
}
}
void exceptionTest::calcVSize()
{
if (toSmallVSize()) throw VSizeError();
}
void exceptionTest::hProcess()
{
if (tooSmallHSize())
{throw HSizeError();
}
}
void exceptionTest::vProcess()
{
calcVSize();
}
void exceptionTest::PerformTest()
{
if (performTeatFail())
{throw PerformError();
}
}
void exceptionTest::metalPieseProcess(int i)
{
hProcess();
PerformTest();
try
{
vProcess();
}
catch (VSizeError &e)
{
cout<<e.what()<<endl;;
cout<<"VSizeError Report"<<endl;
}
}
void exceptionTest::metalGroupProcess(int a)
{
try
{
for (int i = 0; i < 10; i++)
{
metalPieseProcess(i);
}
}
catch (HSizeError* e)
{
cout<<e->what()<<endl;
cout<<"Report HSizeError in metalGroupProcess"<<endl;
}
catch(PerformError &e)
{
cout<<e.what()<<endl;
cout<<"Report PerformError in metalGroupProcess"<<endl;
throw;
}
}
在main函数中,使用调用测试类代码:
exceptionTest *et = new exceptionTest();
et->RunTest();
delete et;
使用多态继承方式捕获异常,体现对象编程的优势。