异常文件处理

Exceptional file handling

我是 c++ 的新手,我正在尝试使用 c++ 实现异常文件处理。 在下面的代码中,我从基础 class 异常.After 运行 我收到错误的代码

error: expected class-name before ‘{’ token {

为什么我需要指定class名称如果我继承它publicly.And如果我需要指定它如何做。

//program to throw an exception if denominator is zero
#include <iostream>
#include <exception>
class Divide_By_Zero_Exception : public exception
{
public:
    const char * what() const throw() {
        return "Divide By Zero Exception";
    }
};
using namespace std;
int main()
{
    Divide_By_Zero_Exception d;
    int n1, n2;
    cin >> n1 >> n2;
    try
    {
        if (n2 == 0)
            throw d;
        else
            cout << n1 / n2;
    }
    catch (exception& e) {
        cout << e.what();
    }
    return 0;
}

它是 std::exception 而不是 exception,因为您的 using-指令在您使用该名称时尚未生效。

此外,而不是

const char * what() const throw()

你可能想写

const char * what() const noexcept