加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么我的异常会在某些配置中被捕获而在其他配置上却没有

发布时间:2020-12-16 06:56:02 所属栏目:百科 来源:网络整理
导读:我有一个程序抛出了一些异常,这个异常在某些配置(Suse Linux,g版本4.4.1)上按预期被捕获但显然没有被另一个捕获,这里是:SunOS 5.10,g版本3.3.2.以下是我的异常类的实现: CException.hpp: #ifndef _CEXCEPTION_HPP#define _CEXCEPTION_HPP#include string#
我有一个程序抛出了一些异常,这个异常在某些配置(Suse Linux,g版本4.4.1)上按预期被捕获但显然没有被另一个捕获,这里是:SunOS 5.10,g版本3.3.2.以下是我的异常类的实现:

CException.hpp:

#ifndef _CEXCEPTION_HPP
#define _CEXCEPTION_HPP

#include <string>
#include <sstream>
#include <exception>
#include <stdlib.h>
#include <iostream>

class CException : public std::exception {
public:
    CException();
    CException(const std::string& error_msg);
    CException( const std::stringstream& error_msg );
    CException( const std::ostringstream& error_msg );
    virtual ~CException() throw();
    const char* what() const throw();
    static void myTerminate()
    {
        std::cout << "unhandled CException" << std::endl;
        exit(1);
    };
private:
  std::string m_error_msg;

};

CException.cpp:

#include "CException.hpp"
#include <string>
#include <sstream>

CException::CException()
{
    std::set_terminate(myTerminate);
    m_error_msg = "default exception";
}

CException::CException(const std::string& error_msg)
{
    std::set_terminate(myTerminate);
    m_error_msg = error_msg;
}

CException::CException(const std::stringstream& error_msg)
{
    std::set_terminate(myTerminate);
    m_error_msg = error_msg.str();
}

CException::CException(const std::ostringstream& error_msg)
{
    std::set_terminate(myTerminate);
    m_error_msg = error_msg.str();
}

CException::~CException() throw()
{
}

const char* CException::what() const throw()
{
    return m_error_msg.c_str();
}
#endif  /* _CEXCEPTION_HPP */

不幸的是,我无法创建一个简单的程序来重现这个问题,但我会尝试概述代码.
在某些文件Auxiliary.cpp中的函数foo()中抛出异常:

std::ostringstream errmsg;
//...
errmsg << "Error occured.";
throw CException( errmsg );

函数foo()用于主程序:

#include Auxiliary.hpp
//...
int main( int argc,char** argv )
{
  try {
    //...
    foo();
  } catch ( CException e ) {
    std::cout << "Caught CException" << std::endl;
    std::cout << "This is the error: " << e.what( ) << std::endl;
  } catch ( std::exception& e ) {
    std::cout << "std exception: " << e.what( ) << std::endl;
  } catch ( ... ) {
    std::cout << "unknown exception: " << std::endl;
  }

我可以看到,当程序以打印未处理的CException(由myTerminate()定义)退出时,不会捕获该异常.

我已经尝试了GNU编译器的-fexceptions选项而没有成功.两个系统上的编译器选项实际上是相同的.

目前我无法弄清问题是什么.任何想法都表示赞赏.谢谢!

解决方法

我发现问题是由使用Fortran95编译器引起的.它在Sun机器上构建程序时用作链接器,在其他机器上使用g.我不知道究竟是什么问题,但我想我也会在Sun机器上切换到g.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读