c++ - 当错误存在时,为什么我的程序不执行第二个 catch block ?

标签 c++ exception try-catch

我是 try/catch 异常处理的新手,想知道为什么我的第二个 catch block 不会执行。 sec 变量不应介于 0-59 之间,因此我希望它显示“无效的第二个条目”,但事实并非如此。谢谢!

#include <stdexcept>
#include <iostream>
#include <string>

using namespace std;


class BadHourError : public runtime_error
{
    public:
    BadHourError() : runtime_error("") {}
};

class BadSecondsError : public runtime_error
{
    public:
    BadSecondsError() : runtime_error("") {}
};

class Time
{
protected:
    int hour;
    int min;
    int sec;
public:
    Time()
    {
        hour = 0; min = 0; sec = 0;
    }

    Time(int h, int m, int s)
    {
        hour = h, min = m, sec = s;
    }

    int getHour() const
    {return hour;}

    int getMin() const
    {return min;}

    int getSec() const
    {return sec;}
};

class MilTime : public Time
{
protected:
    int milHours;
    int milSeconds;

public:
    MilTime() : Time()
    {
    setTime(2400, 60);
    }

    MilTime(int mh, int ms, int h, int m, int s) : Time(h, m, s)
    {
    milHours = mh;
    milSeconds = ms;
    getHour();
    getMin();
    getSec();
    }

    void setTime(int, int);
    int getHour(); //military hour
    int getStandHr(); 
};

void MilTime::setTime(int mh, int ms)
{
milHours = mh;
milSeconds = ms;
sec = milSeconds;
getSec();
}

int MilTime::getHour()
{
return milHours;
}

int MilTime::getStandHr()
{
return hour;
}


int main()
{
MilTime Object;

try
{
if ( (Object.getHour() < 0) || (Object.getHour() > 2359) ) throw BadHourError();
if ( (Object.getSec()  < 0) || (Object.getSec()  > 59  ) ) throw BadSecondsError();
}

catch (const BadHourError &)
{
cout << "ERROR, INVALID HOUR ENTRY";
}

catch (const BadSecondsError &)
{
cout << "ERROR, INVALID SECOND ENTRY";
}
return 0;
}

最佳答案

throw will return control to the next matching exception handler .在这种情况下,下一个执行的 block 将是您的 catch (const BadHourError &),因此甚至永远不会评估 Object.getSec()。你在这里的处理是正确的,它会 throw 但如果你的第一个 if 语句 throw 而不是。

你可以这样做:

try
{
    if ( (Object.getHour() < 0) || (Object.getHour() > 2359) )
       throw BadHourError();
}
catch (const BadHourError &)
{
    cout << "ERROR, INVALID HOUR ENTRY";
}

try
{
    if ( (Object.getSec()  < 0) || (Object.getSec()  > 59  ) )
        throw BadSecondsError();
}
catch (const BadSecondsError &)
{
    cout << "ERROR, INVALID SECOND ENTRY";
}

现在它们将彼此分开处理,确保它们都得到测试;但是,您需要决定是否值得同时测试两者。如果一个小时无效,那么一切正确或无效又有什么关系呢?您的类(class)可能无法正常运行,因此 getSec() > 59 if getHour() > 2359

并不重要

关于c++ - 当错误存在时,为什么我的程序不执行第二个 catch block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36276006/

相关文章:

Java try-catch 未捕获异常

c# - 中断长时间运行的方法模式

c++ - 如何使 void* 参数在函数中保存其局部结果,该函数使用 struct * 调用?

c++ - 使用 boost 序列化保存和检索多个对象

c++ - Boost C++ 单例错误 LNK2001 : unresolved external symbol "private: static long Nsp::HL::flag" (? flag@HL@Nsp@@0JA)

c++ - 编写多线程异常安全代码

.net - 帮助解决 System.BadImageFormatException :

java - try/catch 捕获异常后继续执行循环

c++ - 避免使用禁用的复制构造函数进行隐式复制

c# - 为什么 .NET 异常不适用于接口(interface)而不是基类?