繁体   English   中英

如何在C ++程序中使用异常?

[英]how to use Exceptions in C++ program?

嗨,我正在尝试继承异常类并创建一个名为NonExistingException的新类:我在h文件中编写了以下代码:

class NonExistingException : public exception
{
public:
    virtual const char* what() const throw()  {return "Exception: could not find 
     Item";}
};

在我将代码发送到我正在编写的函数之前

try{
    func(); // func is a function inside another class
}
catch(NonExistingException& e)
{
    cout<<e.what()<<endl;
}
catch (exception& e)
{
     cout<<e.what()<<endl;
}

在func内部,我抛出了异常,但没有发现异常。 在此先感谢您的帮助。

我会这样做:

// Derive from std::runtime_error rather than std::exception
// runtime_error's constructor can take a string as parameter
// the standard's compliant version of std::exception can not
// (though some compiler provide a non standard constructor).
//
class NonExistingVehicleException : public std::runtime_error
{
    public:
       NonExistingVehicleException()
         :std::runtime_error("Exception: could not find Item") {}
};

int main()
{
    try
    {
        throw NonExistingVehicleException();
    }
    // Prefer to catch by const reference.
    catch(NonExistingVehicleException const& e)
    {
        std::cout << "NonExistingVehicleException: " << e.what() << std::endl;
    }
    // Try and catch all exceptions
    catch(std::exception const& e)
    {
        std::cout << "std::exception: " << e.what() << std::endl;
    }
    // If you miss any then ... will catch anything left over.
    catch(...)
    {
        std::cout << "Unknown exception: " << std::endl;
        // Re-Throw this one.
        // It was not handled so you want to make sure it is handled correctly by
        // the OS. So just allow the exception to keep propagating.
        throw;

        // Note: I would probably re-throw any exceptions from main
        //       That I did not explicitly handle and correct.
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM