Catch with multiple parameters
First I found in cplusplus.com the following quote:
The catch format is similar to a regular function that always has at least one parameter.
But I tried this:
try
{
int kk3,k4;
kk3=3;
k4=2;
throw (kk3,"hello");
}
catch (int param)
{
cout << "int exception"<<param<<endl;
}
catch (int param,string s)
{
cout<<param<<s;
}
catch (char param)
{
cout << "char excepti开发者_如何学JAVAon";
}
catch (...)
{
cout << "default exception";
}
The compiler doesn't complain about the throw with braces and multiple arguments. But it actually complains about the catch with multiple parameters in spite of what the reference said. I'm confused. Does try
and catch
allow this multiplicity or not? And what if I wanted to throw an exception that includes more than one variable with or without the same type.
(kk3, "hello") is a comma expression. The comma expression evaluates all of its arguments from left to write and the result is the rightmost argument. So in the expression
int i = (1,3,4);
i becomes 4.
If you really want to throw both of them (for some reason) you could throw like this
throw std::make_pair(kk3, std::string("hello"));
and catch like this:
catch(std::pair<int, std::string>& exc)
{
}
And a catch clause has exactly one argument or
...
HTH
In addition to the other answers, I would recommend you to create your own exception class that can contain more than one piece of information. It should preferably derive from std::exception
. If you make this a strategy, you can always catch your exceptions with a single catch(std::exception&)
(useful if you only want to free some resource, and then rethrow the exception - you don't have to have a gazilion catch handlers for each and every exception type you throw).
Example:
class MyException : public std::exception {
int x;
const char* y;
public:
MyException(const char* msg, int x_, const char* y_)
: std::exception(msg)
, x(x_)
, y(y_) {
}
int GetX() const { return x; }
const char* GetY() const { return y; }
};
...
try {
throw MyException("Shit just hit the fan...", 1234, "Informational string");
} catch(MyException& ex) {
LogAndShowMessage(ex.what());
DoSomething(ex.GetX(), ex.GetY());
}
精彩评论