Home > OS >  Constructor with exception handling for invalid input c
Constructor with exception handling for invalid input c

Time:03-18

I'm trying to create a constructor that validates input and throws an exception if the input is invalid.

Let's say I have a constructor that only accepts values in mod 12 for int a, values of mod 16 for b, and values greater than 0 for c. I'm trying to use the std::invalid_argument. How would I implement the exception handler? Would this throw an exception? If the values entered were out of bound?

Mod(int a, int b, int c) {
   try {
       if (a > 11 || a < 0 || b > 15 || b < 0 || c < 0) {
           throw std::invalid_argument("Invalid Argument");
       }
   } catch (std::invalid_argument const& value) {
       std::cerr << "Invalid Argument " << value.what() << '\n';
   }
}

CodePudding user response:

Would this throw an exception?

Yes, but then you catch the exception, so the constructor would return successfully.

If your goal is to throw out of the constructor, then don't catch the exception in the constructor.

How would I implement the exception handler?

You would implement the exception handler in the scope where you want to handle the exception. You cannot handle the exception in the scope where you want to throw the exception out of.

CodePudding user response:

How would I implement the exception handler?

By NOT implementing it in the constructor that is throwing. Implement it in the code that is trying to pass invalid input to the constructor, eg:

Mod(int a, int b, int c){
   if (a > 11 || a < 0 || b > 15 || b < 0 || c < 0 ) {
      throw std::invalid_argument("Invalid Argument");
   }
}
try {
   Mod m(1, 2, -1);
   // use m as needed...
}
catch (std::invalid_argument const& value) {
    std::cerr << "Invalid Argument " << value.what() << '\n';
}

Would this throw an exception? If the values entered were out of bound?

Yes, it does, but then it immediately catches and discards the exception, so the caller will never see it. It may as well have never been thrown.

  • Related