2017-10-19 146 views
0

我读what-is-the-purpose-of-stdexceptionwhat和引用的std::exceptionhere从性病::例外比为const char *

定义我需要从std::exception::what()返回int,因为它是virtual但我可以返回不同类型::什么()等不会被返回类型覆盖。我滚我自己的异常类

class BadLengthException : public std::exception 
{ 
private: 
    int length; 
    const char* to_return; 
public: 
    BadLengthException() = default; 
    BadLengthException(int new_length) : length(new_length) { to_return = new const char(length); } 
    ~BadLengthException() = default; 
    const char* what() const throw() { return to_return; } 

}; 

我将如何能够改变返回类型纯int适合我的需求,使得

try 
{ 
} 
catch(BadLengthException bad_length) 
{ 
    std::cout << bad_length.what() <------- Got your int value 
} 

编辑我更改了代码。测试显示它提供了正确的值。我可以改进我所做的事吗?考虑到我必须总是返回const char*

class BadLengthException : public std::exception 
{ 
private: 
    const size_t size = 2; 
    char ref_arr[5] = { '1','2','3','4','5' }; 
    int length; 
    char* to_return; 
public: 
    BadLengthException() = default; 
    BadLengthException(int new_length) : length(new_length) 
    { 
     to_return = (char*)malloc(size * sizeof(char)); 
     to_return[0] = ref_arr[length - 1]; 
     to_return[1] = '\0'; 
    } 
    ~BadLengthException() = default; 
    const char* what() const throw() override { return to_return; } 

}; 
+1

你不知道。为什么不只是添加一个额外的方法?然后,你的异常的捕手可以说'bad_length.length()'或者其他。 – GManNickG

+0

@GManNickG在这个特殊的问题,我正在解决,预期的输出只限于'std :: exception :: what()' – Mushy

+0

_I需要使用什么,因为我需要使用what_ ok – 2017-10-19 18:27:51

回答

0

你不这样做。

如果你必须这样做:

struct custom_error:std::exception { 
    const char* what() const throw() override final { return str.c_str(); } 
    explicit custom_error(std::string s):str(std::move(s)) {} 
    explicit custom_error(int x):custom_error(std::to_string(x)) {} 
private: 
    std::string str; 
}; 

现在我们存储和返回的序列化描述你的int在缓冲区中,并要求返回一个指针到它。

要转换回:

int main() { 
    try { 
    throw custom_error(34); 
    } catch (std::exception const& ex) { 
    std::stringstream ss(ex.what()); 
    int x; 
    if (ss >> x) { 
     std::cout << "X is " << x << "\n"; 
    } 
    } 
} 

Live example