错误类型自定义

来源:互联网 发布:证券开户 知乎 编辑:程序博客网 时间:2024/05/29 08:36

.h文件

#pragma once

#include <string>
#include <stdexcept>

class ArdError : public std::logic_error
{
public:
 enum ARD_ERROR_TYPE {
  FILE_OPEN_FAILURE,
  FILE_READ_FAILURE,

 };

 ArdError(const char * errMsg);
 ArdError(std::string errMsg);
 ArdError(ARD_ERROR_TYPE errType);
 ArdError(ARD_ERROR_TYPE errType, exception* e);
 ~ArdError(void);

 ARD_ERROR_TYPE GetErrorType(void) { return _errorType; }
private:
 ARD_ERROR_TYPE _errorType;
 exception* _exception;


 inline const char * getErrMsg(ARD_ERROR_TYPE errType);
};

.cpp文件


#include "./ArdError.h"

static const char * ERROR_MESSAGE[] = {
 "open file fail, please check file path and file permission",
 "read file fail, please check file path and file permission"
};

ArdError::ArdError(const char * errMsg)
: logic_error(errMsg), _errorType(COMMON), _exception(NULL)
{
}

ArdError::ArdError(std::string errMsg)
: logic_error(errMsg.c_str()), _errorType(COMMON), _exception(NULL)
{
}

ArdError::ArdError(ARD_ERROR_TYPE errType)
 : logic_error(ERROR_MESSAGE[errType]), _errorType(errType), _exception(NULL)
{
 
}

ArdError::ArdError(ARD_ERROR_TYPE errType, exception* e)
 : logic_error(ERROR_MESSAGE[errType]), _errorType(errType), _exception(e)
{
}

ArdError::~ArdError(void)
{
}

inline const char * ArdError::getErrMsg(ARD_ERROR_TYPE errType) {

 return ERROR_MESSAGE[errType];
}

应用例子:

try {

  CsvFile::ReadCsvAttData(filename, spShpCon);

}

 catch(ArdError &e)
 {
  if(e.GetErrorType() == ArdError::FILE_OPEN_FAILURE );

}

原创粉丝点击