2016-03-29 4 views
0

私はtry/catch例外処理の初心者で、なぜ2番目のcatchブロックが実行されないのだろうと思っています。 sec変数は0〜59の間であってはなりません。したがって、「無効な2番目のエントリ」と言いたいのですが、そうではありません。ありがとうございました!エラーが存在する場合、私のプログラムは2番目のcatchブロックを実行しません。なぜですか?

#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; 
} 

答えて

1

throw will return control to the next matching exception handler。この場合、実行される次のブロックは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"; 
} 

今、彼らは両方の検査を受ける確保し、それぞれ別々に処理されます。ただし、両方をテストする価値があるかどうかを判断する必要があります。 1時間が無効な場合、すべてが正しいか無効であれば何が問題になりますか?あなたのクラスはおそらくうまく機能しないかもしれませんので、それは問題ではありません。getSec() > 59の場合getHour() > 2359

+0

この単純なプログラムでは、 'if((Object.getSec()<0)||(Object。 getSec()> 59))cout << try/catchがどのように動作するかを学習していない限り、 "ERROR、INVALID SECOND ENTRY"; – immibis

0

milHourが2400なので、悪い時間に例外がスローされるためです。

関連する問題