【发布时间】:2015-12-22 16:33:10
【问题描述】:
我正在使用以下代码编写自定义异常类:
#include <iostream>
#include <string>
#include <memory>
#include <sstream>
#include <iomanip>
#include <algorithm>
class MyException : public std::exception {
public:
MyException();
explicit MyException(std::string message);
MyException(std::string source, std::string message);
MyException(int code, std::string source, std::string message);
const char *what() const throw();
private:
int exceptionCode;
std::string exceptionSource;
std::string exceptionMessage;
};
MyException::MyException() :
exceptionCode(0),
exceptionSource ("No source."),
exceptionMessage ("No message.") {}
MyException::MyException(std::string message) :
exceptionCode(0),
exceptionSource ("No source."),
exceptionMessage (std::move(message)) {}
MyException::MyException(std::string source, std::string message) :
exceptionCode(0),
exceptionSource (std::move(source)),
exceptionMessage (std::move(message)) {}
MyException::MyException(int code, std::string source, std::string message) :
exceptionCode(code),
exceptionSource (source),
exceptionMessage (message) {}
const char *MyException::what() const throw()
{
std::cout << "What:" << exceptionMessage << std::endl;
std::stringstream s;
s << "MyException Data:" << std::endl;
s << "Code : " << exceptionCode << std::endl;
s << "Source : " << exceptionSource << std::endl;
s << "Message : " << exceptionMessage << std::endl;
std::string whatString = s.str();
return whatString.c_str();
}
void test()
{
throw new MyException("test", "This is a test");
}
int main()
{
try
{
test();
}
catch (const std::exception &exc)
{
std::cerr << "Exception detected:" << std::endl;
std::cerr << exc.what();
throw exc;
}
catch (...)
{
std::cerr << "An unknown exception was called." << std::endl;
throw;
}
}
它编译得很好,但我无法从 catch (const std::exception &exc) 块中捕获我自己的异常。它只被catch (...) 块捕获。
由于MyException 是从std::exception 继承的,我想它会被第一个catch 块捕获...为什么没有发生?
原码链接here
【问题讨论】:
-
您已经编写了太多 Java(或 C# 或其他)。放弃
new- 你正在抛出MyException*。 -
请注意,您从
what返回的指针在函数返回后立即失效且无法使用。 -
多么悲惨的声明
new...感谢您的帮助。 -
如果您是从 Java 背景开始接触 C++,那么现在就是尝试忘记它的好时机。
-
除非确实需要,否则不要使用
std::endl。'\n'结束一行,没有刷新流的开销。