C++ 运行时,显示异常信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2715386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:27:40  来源:igfitidea点击:

C++ runtime, display exception message

c++exception

提问by Anycorn

I am using gcc on linux to compile C++ code. There are some exceptions which should not be handled and should close program. However, I would like to be able to display exception string:

我在 linux 上使用 gcc 来编译 C++ 代码。有一些不应该被处理并且应该关闭程序的异常。但是,我希望能够显示异常字符串:

For example:

例如:

throw std::runtime_error(" message");does not display message, only type of error. I would like to display messages as well. Is there way to do it?

throw std::runtime_error(" message");不显示消息,只显示错误类型。我也想显示消息。有办法吗?

it is a library, I really do not want to put catch statements and let library user decide. However, right now library user is fortran, which does not allow to handle exceptions. in principle, I can put handlers in wrapper code, but rather not to if there is a way around

它是一个库,我真的不想放置 catch 语句并让库用户决定。但是,现在库用户是fortran,它不允许处理异常。原则上,我可以将处理程序放在包装器代码中,但如果有办法的话就不要这样做

回答by

Standard exceptions have a virtual what()method that gives you the message associated with the exception:

标准异常有一个虚what()方法,它为您提供与异常相关的消息:

int main() {
   try {
       // your stuff
   }
   catch( const std::exception & ex ) {
       cerr << ex.what() << endl;
   }
}

回答by EFraim

You could write in main:

你可以在 main 中写:

try{

}catch(const std::exception &e){
   std::cerr << e.what() << std::endl;
   throw;
}

回答by Kirill V. Lyadvinsky

You could use try/catchblock and throw;statement to let library user to handle the exception. throw;statement passes control to another handler for the same exception.

您可以使用try/catch块和throw;语句让库用户处理异常。throw;语句将控制权传递给相同异常的另一个处理程序。

回答by frankc

I recommend making an adapter for your library for fortran callers. Put your try/catch in the adapter. Essentially your library needs multiple entry points if you want it to be called from fortran (or C) but still allow exceptions to propigate to C++ callers. This way also has the advantage of giving C++ linkage to C++ callers. Only having a fortran interface will limit you substantially in that everything must be passed by reference, you need to account for hidden parameters for char * arguments etc.

我建议为您的库为 fortran 调用者制作一个适配器。将您的 try/catch 放入适配器中。如果您希望从 fortran(或 C)调用它,但仍然允许异常传播到 C++ 调用者,那么基本上您的库需要多个入口点。这种方式还具有为 C++ 调用者提供 C++ 链接的优点。只有一个 fortran 接口会大大限制你,因为一切都必须通过引用传递,你需要考虑 char * 参数等的隐藏参数。