我的任务是:基于我的项目,创建从std::exception传递的异常类,并实现虚拟函数what()。
在读/写文件、转换/读取数据类型、创建不同的类成员等过程中,可能会导致项目中可能出现的异常。
我试着这样做:
#include <stdexcept>
#define MYEXCEPTION(exception_name)
struct exception_name : public ::std::runtime_error
{
typedef ::std::runtime_error
Base;
explicit exception_name(const std::string& msg)
: Base(msg) {}
explicit exception_name(const char* msg)
: Base(msg) {}
};
#include <iostream>
#include <string>
#include <exception>
class Catch: public std::exception
{
public:
Catch() :exceptionCode(0), exceptionSource("no source"), exceptionMessage("no message") {SetError(my_ex);}
explicit Catch(std::string message) :exceptionCode(0), exceptionSource("no source"), exceptionMessage(std::move(message)) { SetError(my_ex); }
Catch(std::string source, std::string message) :exceptionCode(0), exceptionSource(std::move(source)), exceptionMessage(std::move(message)) { SetError(my_ex); }
Catch(int code, std::string source, std::string message):exceptionCode(code), exceptionSource(std::move(source)), exceptionMessage(std::move(message)) { SetError(my_ex); }
const char* what() const noexcept { return ((*error).c_str()); }
private:
const std::string my_ex = ("CODE:" + std::to_string(exceptionCode) + "\n" + "SOURCE:" + exceptionSource + "\n" + "MESSAGE:" + exceptionMessage + "\n");
void SetError(std::string ex) { error = &ex; }
int exceptionCode;
std::string exceptionSource;
std::string exceptionMessage;
std::string* error;
};
class ObjectException : public Catch {
public:
ObjectException(char* message, int state): Catch(message) { this->state = state; }
int GetState(void) { return state; }
private:
int state;
};
class FileException : public std::exception {
FileException(std::string destination, std::string path, std::string message): message(message.c_str()) {}
const char* what() const throw() { return "FileException occured\n"; }
private:
std::string message;
std::string destination;
};
class DataException : public std::exception {
public:
DataException(char* message, int state) :exception(message) {
this->state = state;
}
int GetState(void) { return state; }
const char* what() const throw() { return "DataException:invalid_type\n"; };
private:
int state;
};
class Exception : public std::exception
{
std::string _msg;
public:
Exception(const std::string& msg) : _msg(msg) {}
virtual const char* what() const noexcept override
{
return _msg.c_str();
}
};
但是,当我尝试时:
#include "catch.h"
void Polygon_m::Define() {
std::ifstream input;
input.open(path);
if (input.is_open())
std::cout << "Polygon_m::Defining_file:found" << std::endl;
else
throw FileException("Polygon_m::Defining_file:", path , ":failed");
..........
}
我有:
FileException::FileException(…)(在行中声明…)无法访问
请给我一些如何做的建议,我整个星期都在努力探索这个话题。一定是这样
非常
易于理解的
我已经读了很多与我的问题相关的帖子,但问题是我对这个话题没有感觉。我找不到任何书或文章来解释我需要的细节。如果你知道一个,请给我一个链接。