文章目录
- 1.异常类
- 2.表达式计算机增加异常处理
1.异常类
- P52\Exception.h,P52\Exception.cpp
#ifndef _EXCEPTION_H_
#define _EXCEPTION_H_
#include <exception>
#include <string>
//继承至标准库的exception类
class Exception : public std:exception
{
public:
//为了防止转换构造
explicit expException(const char* message) : message_(message)
{
FillStackTrace();
}
//析构函数不抛出异常,throw()表示不抛出异常
virtual ~Exception() throw()
{
}
//what是基类的虚函数,这里覆盖waht方法,也不抛出异常
virtual const char* what() const throw();
const char* StackTrace() const throw();
private:
void FillStackTrace();
std:string message_;
std::string stackTrace_;//在发生异常的地方,将调用栈信息保存到字符串stackTrace_中
//在构造throw SyntaxError("Not a valid expression");对象的时候就把当前的调用栈信息,栈回溯写入到stackTrace_变量中
};
//语法错误
class SyntaxError : public Exception
{
public:
explicit SyntaxError(const char* message) : Exception(message)
{
}
virtual ~SyntaxError() throw()
{
}
//这里不再覆盖what方法
};
#endif //_EXCEPTION_H_
2.表达式计算机增加异常处理
- P52\main.cpp,P52\Parser.cpp,P52\SymbolTable.cpp
throw以及try catch语句
- 测试:左值不是一个变量
这一次的异常不影响下一次的表达式计算,仅仅是这个语法错误而已
因式缺少右括号的异常测试
函数调用的时候,是一个不认识的函数
函数调用中缺少右括号的异常测试。ff(2,先判定是否缺少右括号,再判定是否是一个合法的函数