自定义异常类 C++

Custom Exception Class C++

本文关键字:C++ 自定义异常      更新时间:2023-10-16

我会写一个自定义异常类,但这是不可能的,因为我有一个错误。

SSException.h :

#ifndef SSEXCEPTION_H
#define SSEXCEPTION_H
#include <iostream>
#include <exception>
class SSException: public std::exception {
public :
    virtual const char* what() const throw();
private:
    const char* errMessage_;
};
#endif

SSException.cpp :

using namespace std;
const char* SSException::what() const throw()
{
    return "UNKNOW";
}

我会有一个自定义方法,例如:Virtual const char* getMsg(int code);

但是这个解决方案,行不通。你可以帮我吗?实现:

try {
   st.timeRef();
    }   catch(const SSException& ex)    {
        //cerr << "Solar System Exception: n" << ex.what() << endl;
        cerr << "Solar System Exception: n" << ex.getMsg(2) << endl;
    }

错误:

SolarSystem.cpp:26:54:错误:将"const SSException"传递为"this" 'Virtual const char* SSException::getMsg(int)' 的参数丢弃 限定符 [-允许] cerr <<"太阳系异常:" << ex.getMsg(2) <<endl;

提前谢谢你

我会有一个自定义方法,例如:虚拟常量字符* getMsg(int code);

它需要virtual const char* getMsg(int code) const;,因为你的代码通过不断的引用来捕获。在这种情况下const仅表示函数getMsg不会修改其对象。