cout << future_value(1000, -100, -1);
double future_value(double initial_balance, double p, int n)
{ return initial_balance * pow(1 + p / 100, n);
}
double future_value(double initial_balance, double p, int n)
{ if (p < 0 || n < 0) return 0;
return initial_balance * pow(1 + p / 100, n);
}
double future_value(double initial_balance, double p, int n)
{ assert(p >= 0 && n >= 0);
return initial_balance * pow(1 + p / 100, n);
}
double future_value(double initial_balance, double p, int n)
{ if (p < 0 || n < 0)
{ logic_error description("illegal future_value parameter");
throw description;
}
return initial_balance * pow(1 + p / 100, n);
}
double future_value(double initial_balance, double p, int n)
{ if (p < 0 || n < 0)
throw logic_error("illegal future_value parameter");
return initial_balance * pow(1 + p / 100, n);
}
Syntax 17.8: Throwing an Exception throw expression;
|
try
{
// code
}
catch (logic_error& e)
{
// handler
}
while (more)
{ try
{
// code
}
catch (logic_error& e)
{ cout << "A logic error has occurred "
<< e.what() << "\n" << "Retry? (y/n)";
string input;
getline(cin, input);
if (input == "n") more = false;
}
}
Syntax 17.9: Try Block try
|
class FutureValueError : public logic_error {
public:
FutureValueError(const char reason[]);
};
FutureValueError::FutureValueError(const char reason[])
: logic_error(reason){}
if (p < 0 || n < 0)
throw FutureValueError("illegal parameter");
try
{
// code
}
catch (FutureValueError& e)
{
// handler1
}
catch (logic_error& e)
{
// handler2
}
bool Product::read(fstream& fs)
{ getline(fs, name);
if (name == "") return false; // end of file
fs >> price >> score;
if (fs.fail())
throw runtime_error("Error while reading product");
string remainder;
getline(fs, remainder);
return true;
}
void process_products(fstream& fs)
{ vector<Product> products;
bool more = true;
while (more)
{ Product p;
if (p.read(fs)) products.push_back(p);
else more = false;
}
// do something with products
}
Product* p = new Product();
if (p->read())
{
...
}
delete p; // never executes if read throws an exception
Product* p = NULL;
try
{ p = new Product();
if (p->read())
{
...
}
delete p;
}
catch(...)
{ delete p;
throw;
}
void process_products(fstream& fs)
throw (UnexpectedEndOfFile, bad_alloc)
void process_products(fstream& fs)
throw ()
Syntax 17.10: Exception Specification return_type function_name(parameters)
|