C++ 抛出异常
我在这样一个函数中创建了一个异常:C++ 抛出异常,c++,visual-studio-2010,exception,C++,Visual Studio 2010,Exception,我在这样一个函数中创建了一个异常: void testing(int &X) { .... X=... if (X>5) throw "X greater than 5!" } 然后是main.cpp try { int X=0; testing(X); } catch (const char *msgX) { .... } 但现在我还要介绍Y作为X。测试的原型将是: void testing(int &X, int &Y) 5&&Y>5)抛出myexce
void testing(int &X)
{
....
X=...
if (X>5)
throw "X greater than 5!"
}
然后是main.cpp
try
{
int X=0;
testing(X);
}
catch (const char *msgX)
{
....
}
但现在我还要介绍Y作为X。测试的原型将是:
void testing(int &X, int &Y)
<我的问题,我怎么能抛出两个例外,如果x>5,我抛出一个关于x的异常,如果y>10,我在y的另一个异常上,y在i的主程序中结束时,在C++中,不可能有两个例外“在飞行中”。如果出现这种情况(例如,在堆栈展开期间由析构函数抛出),程序将终止(无法捕获第二个异常) 您可以做的是创建一个合适的异常类,并抛出它。例如:
class my_exception : public std::exception {
public:
my_exception() : x(0), y(0) {} // assumes 0 is never a bad value
void set_bad_x(int value) { x = value; }
void set_bad_y(int value) { y = value; }
virtual const char* what() {
text.clear();
text << "error:";
if (x)
text << " bad x=" << x;
if (y)
text << " bad y=" << y;
return text.str().c_str();
}
private:
int x;
int y;
std::ostringstream text; // ok, this is not nothrow, sue me
};
无论如何,您永远不应该抛出原始字符串或整数或类似的东西——只抛出从std::exception派生的类(或者您最喜欢的库的异常类,它们可能会从std::exception派生,但可能不会)。您可以抛出不同的异常类型,也可以通过具有不同内容的相同异常类型
struct myexception : public std::exception
{
std::string description;
myexception(std::string const & ss) : description(ss) {}
~myexception() throw () {} // Updated
const char* what() const throw() { return description.c_str(); }
};
void testing(int &X, int &Y)
{
if (X>5)
throw myexception("X greater than 5!")
if (Y>5)
throw myexception("Y greater than 5!")
}
try
{
int X=0;
testing(X);
}
catch (myexception const & ex)
{
}
(顺便说一句,我没有否决投票…)
这是一张草图:
class x_out_of_range : public std::exception {
virtual const char* what() { return "x > 5"; }
};
class y_out_of_range : public std::exception {
virtual const char* what() { return "y > 10"; }
};
现在在您的功能中:
if (x > 5)
throw x_out_of_range();
:
if (y > 10)
throw y_out_of_range();
现在,您的捕获代码:
try
{
:
}
catch (x_out_of_range const& e)
{
}
catch (y_out_of_range const& e)
{
}
注意:在任何情况下,您只能从函数中抛出一个异常…提示:创建一个特定的类来表示每种类型的异常,然后抛出每种异常的实例,然后您可以单独捕获它们…我不明白为什么要将-1放在这里?您可能会感兴趣:如果我正确理解您想要做什么,那就不可能了。当抛出异常时,控制转移到catch处理程序,因此抛出异常的函数的其余部分不会执行。您不能从对
测试的单个调用中抛出多个异常。当然,如果(X>5&&Y>5)抛出myexception(“X和Y都太大了”),没有什么可以阻止您执行代码>第一个。@ItwastPete:是的,这就是为什么我在代码中写了关于nothrow的注释。在写THOW“…”时,在移到主程序之前,是否可以在末尾检查是否有东西要抛出?
try
{
:
}
catch (x_out_of_range const& e)
{
}
catch (y_out_of_range const& e)
{
}