Using an exception class - C++ Class

C++ examples for Class:Exception Class

Description

Using an exception class

Demo Code

#include <iostream>
#include <algorithm>                        // For min() function template
#include <stdexcept>                         // For derived exception classes
#include <string>

using std::string;
using std::range_error;

class dimension_error : public range_error
{
public:/*from   w w  w  . j  a v a  2  s .c o  m*/
  using range_error::range_error;          // Inherit base constructors

  dimension_error(std::string str, double dim) : range_error {str + std::to_string(dim)} {}
};

class Pool
{
protected:
  double length {1.0};
  double width {1.0};
  double height {1.0};

public:
  Pool(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv}
  {
    if(lv <= 0.0 || wv <= 0.0 || hv <= 0.0)
      throw dimension_error {"Zero or negative Pool dimension.", std::min(lv, std::min(wv, hv)) };
  }

  double volume() const { return length*width*height; }
};


int main()
try
{
  Pool pool1 {1.0, 2.0, 3.0};
  std::cout << "pool1 volume is " << pool1.volume() << std::endl;
  Pool pool2 {1.0, -2.0, 3.0};
  std::cout << "pool1 volume is " << pool2.volume() << std::endl;
}
catch (std::exception& ex)
{
  std::cout << "Exception caught in main(): " << ex.what() << std::endl;
}

Result


Related Tutorials