0

I'm new to exception handling and this is a question about a problem I'm having on one of my first assignments on the subject. I have purposely gave the program an invalid entry for hours and seconds to test out the try/catch, so both should throw an exception. I kind of get why the first catch block catches both throws, but I'm not sure then how to get it to use both catch blocks? Thanks! (output is "ERROR: INVALID HOUR ENTRY")

int main()
{
MilTime Object;
string BadHour;
string BadSeconds;

try
{
if ( (Object.getHour() < 0) || (Object.getHour() > 2359) ) throw BadHour;
if ( (Object.getSec()  < 0) || (Object.getSec()  > 59  ) ) throw BadSeconds;
}
catch (string BadHour)
{
cout << "ERROR, INVALID HOUR ENTRY";
}
catch (string BadSeconds)
{
cout << "ERROR, INVALID SECOND ENTRY";
}
return 0;

3 Answers 3

2

catches are differentiated by type, not by argument names.

In principle you could define different exception types, or you could use e.g. std::system_error which allows you to pass an integer error id.

However, in practice the particular cause of an exception is of little interest other than for logging, because it generally doesn't affect what to do about it. An exception says that the code has failed to do what its contract said it should do. A catch can only try to do whatever that goal was, again (possibly in some different way), or in turn fail.

3
  • Thanks. Does that mean there is a way for me to do what I'm trying to do? I'd like to implement the first message being read if the hour entered is wrong, and the second message being read if the seconds are entered wrong.
    – Ben
    Mar 29, 2016 at 3:55
  • You can pass that message in the exception object, e.g. a std::runtime_error. But in C++ it's very non-idiomatic to use exceptions for expected, frequently occuring conditions. C++ exceptions are designed and typically optimized for rare cases of contract failure. Mar 29, 2016 at 3:57
  • It would make more sense to have MilTime itself throw an exception if assigned a value that it choses to reject as invalid, rather than throwing the exception at some random time after the assignment has been made. Mar 29, 2016 at 4:01
0

You have to catch exceptions by data type, not by variable name. Try something more like this instead:

#include <iostream>
#include <stdexcept> 

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

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

class MilTime
{
public:
    int getHour() const { return ...; }
    int getSec() const { return ...; }
};

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 &)
    {
        std::cout << "ERROR, INVALID HOUR ENTRY";
    }
    catch (const BadSecondsError &)
    {
        std::cout << "ERROR, INVALID SECOND ENTRY";
    }

    return 0;
}

Alternatively:

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

class BadTimeError : public std::runtime_error
{
public:
    BadTimeError(const std::string &what_arg) : std::runtime_error(what_arg) {}
};

class BadHourError : public BadTimeError
{
public:
    BadHourError() : BadTimeError("INVALID HOUR ENTRY") {}
};

class BadSecondsError : public BadTimeError
{
public:
    BadSecondsError() : BadTimeError("INVALID SECOND ENTRY") {}
};

class MilTime
{
public:
    int getHour() const { return ...; }
    int getSec() const { return ...; }
};

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 BadTimeError &ex)
    {
        std::cout << "ERROR, " << ex.what();
    }

    return 0;
}
8
  • Thank you! I don't use std:: , as I've been taught to just include using namespace std at the beginning of my programs. With what you gave me I get the error "Expected class name before { token" in the class BadHourError
    – Ben
    Mar 29, 2016 at 4:06
  • @Ben: "I've been taught to just include using namespace std" - you are being taught wrong! That is used by newbies (and bad professors) who don't know any better. Professional developers do not use that. There are better/safer options, like using using std::string and using std::cout instead if you want to use cout and string instead of std::cout and std::string explicitly. Don't shy away from std::, it exists to protect you, so use it properly. Don't be lazy/sloppy and your code will be better for it. Mar 29, 2016 at 4:13
  • Thank you. I will try to start incorporating std:: , and not using using namespace std; anymore. Any idea on why your code gives me that error though? (the first one)
    – Ben
    Mar 29, 2016 at 4:18
  • @Ben: Works fine for me, I just compiled it without error. Mar 29, 2016 at 4:19
  • I included the <stdexcept> and then it worked for me. However, I still only get the first error message.
    – Ben
    Mar 29, 2016 at 4:38
0

You can see how try/throw/catch is indeed type dependent if you set up your own types i.e. struct's and test as follows:

#include <iostream>

using namespace std;

struct BadHr 
{
};

struct BadSec 
{
};

int main()
{
    int test = 2;

    try
    {
        if (test == 1) throw BadHr();
        if (test == 2) throw BadSec();
    }
    catch (BadHr& e)
    {
        std::cout << "Bad hour" << std::endl;
    }
    catch (BadSec& e)
    {
        std::cout << "Bad Sec" << std::endl;
    }


}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.