c++ - 在 C++ 中将类变量传递给异常

标签 c++ class exception

这是上周测试的(修改后的)问题。 我得到了一个带有预定义数字的异常类:

class ErrorException  {

    /**
    * Stub class.
    */
private :static long ErrorCode;

public: ErrorException( string str) {
                cout <<str;
        }
};

long ErrorException::ErrorCode = -444;

我想我应该做的是捕获异常然后将数字作为错误代码返回,但我不知道如何获取数字。我可以让捕获返回一个字符串而不是数字作为字符串:

#include "stdafx.h"
#include <iostream>
#include "ErrorException.h"

#include "errno.h""
#include <string>;
class FillerFunction {


public :

        virtual int getFillerFunction(int x) throw (ErrorException) = 0;

} // this notation means getFillerFunction is always throwing ErrorException?

double calculateNumber(int y){
//.....
try{
     if (y !=0){
      throw(ErrorException(?????))
      }
};

double catchError(){
      catch(ErrorException& x);
};

我最终让它返回字符串“error”,这并不比使用 if 语句好。我已经在 C++ 和动态异常中查找了其他捕获抛出示例,但我找不到一个异常获取类中定义的变量的示例。如何访问 ErrorCode,保存更改 ErrorException 的返回类型( )?

最佳答案

虽然这个问题已经得到解答,但我只想添加一些关于在 C++11 中正确处理异常的注意事项:

首先,不应使用 throw(ErrorException),因为它已被弃用:http://en.cppreference.com/w/cpp/language/except_spec

此外,通常建议利用 C++ 提供标准异常类这一事实,我个人通常从 std::runtime_error 派生。 .

为了真正利用C++11中的异常机制,我推荐使用std::nested_exceptionstd::throw_with_nested如 StackOverflow 所述 herehere .创建适当的异常处理程序将允许您在代码中获取异常的回溯,而无需调试器或繁琐的日志记录。由于您可以使用派生的异常类来执行此操作,因此您可以向此类回溯添加大量信息! 你也可以看看我的MWE on GitHub ,回溯看起来像这样:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

关于c++ - 在 C++ 中将类变量传递给异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39069398/

相关文章:

c++ MFC从工作线程设置/附加文本到richedit控件

java - PatternSyntaxException 尝试按 },{ 拆分时出现

java - 在 Java 中将类作为参数传递并进行扩展检查

c++ - 类(class)的私有(private)成员在我的类(class)实例化期间发生了变化,即使他们不应该

ruby-on-rails - delayed_job 的 exception_notification

java - 当基类需要捕获异常时,在派生类构造函数中使用 Super

c++ - 为什么这个程序在第一个循环后崩溃?

c++ - 如何防止std::is_constructible中的隐式转换

c++ - LPWSTR 到 std::string?

Javascript:如果存在一个类,如何修改类的属性?