https://rentry.org/PPP2_p147

// Code derived from Stroustrup's PPP2 book
// § 5.6.1 Bad arguments
//  -and beginning on p 147

#include <iostream>

using std::cout;

// a type specifically for reporting errors from area()
class Bad_area {};

// calculate area of a rectangle;
// throw a Bad_area exception in case of a bad argument
int area(int length, int width)
{
  if (length <= 0 || width <= 0)
    throw Bad_area{};

  return length * width;
}

// calculate area within frame
int framed_area(int x, int y)
{
  constexpr int frame_width = 2;

  return area(x - frame_width, y - frame_width);
}

int main()
try {
  int x = -1;
  int y = 2;
  int z = 4;

  // . . .

  int    area1 = area(x, y);
  int    area2 = framed_area(1, z);
  int    area3 = framed_area(y, z);
  double ratio = area1 / area3;

  cout << area1 << '\n'  //
       << area2 << '\n'  //
       << area3 << '\n'  //
       << ratio << '\n';

} catch (Bad_area) {
  cout << "Oops! bad arguments to area()\n";
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_05/main_p147.cpp && ./a.out

PrevUpNext

Edit
Pub: 22 Feb 2023 12:23 UTC
Edit: 29 Apr 2023 09:25 UTC
Views: 392