C++ Exceptions Throw Empty Class
Below is an excerpt from "Programming: Principles and Practice Using C++".
I'm confused by the throw Bad_area() notation. The book tries to explain
it, "Bad_area() means 'Make an object of type Bad_area'," continuing with
that it then throws that type. This explanation is not congruent with the
assignment notation, eg. int x=1 == int x(1); or Bad_area x;.
Example code (commented out the try-block):
class Bad_area {}; // a type specifically for reporting errors from 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;
}
int main()
try {
// ...
}
catch (Bad_area) {
cout << "Oop! bad arguments to area()\n";
}
No comments:
Post a Comment