2015-11-08 53 views
0

我只是学习抛出异常,我写了一个代码,但它似乎并不像我可以打印Error: too bigError:too large当我输入10000100000。我该如何解决这个问题才能打印出Error: too bigError:too large我怎么不能打印出我的抛出异常的错误?

#include<iostream> 
#include<stdexcept> 
using namespace std; 

int main() 
{ 
    int xxx; 
    cout<<"please enter xxx:"; 
    cin>>xxx; 
    if (xxx==1) 
     cout<<"2"; 
    else if (xxx==10) 
     cout<<"3"; 
    else if (xxx==100) 
     cout<<"4"; 
    else if (xxx==1000) 
     cout<<"5"; 
    else if (xxx==10000) 
     throw "too big"; 
    else if (xxx==100000) 
     throw "too large"; 
    return 0; 
} 
+0

您添加一个'尝试{}赶上(为const char * MSG){COUT <<味精<< ENDL; }' –

回答

-3

抛必须写过try块只有这么写在try块中的所有条件,并通过捕捉它们在try块外面进行操作,立即

try 
{ 
condition 
throw exception ; 
} 
catch exception 
{ 
message or correction lines 
} 

+0

必须在try块中写入引发,但这些块可以在调用堆栈的任意位置,而且不必局限于本地。 – Puppy

0

你似乎属性例外情况太神奇了。

但它的核心,例外非常简单。基本上,这只是意味着一些底层代码会创建一个对象(通过throw),最终在一些更高级的代码中(通过catch)。

如果没有catch,那么异常会使函数调用堆栈“下降”,并且它会一直这样做,直到它“脱落”main

发生这种情况时,会发生一系列特殊事件。您可以使用相对较先进的技术来配置行为,但所有初学者确实需要知道的是,您在此情况下不能保证打印任何错误消息时您是。如果你想要一个异常导致错误信息,那么你必须自己编写必要的代码。

适应你的原来的例子,该代码可能看起来像这样:

#include<iostream> 
#include<stdexcept> 
using namespace std; 

int main() 
{ 
    try 
    { 
     int xxx; 
     cout<<"please enter xxx:"; 
     cin>>xxx; 
     if (xxx==1) 
      cout<<"2"; 
     else if (xxx==10) 
      cout<<"3"; 
     else if (xxx==100) 
      cout<<"4"; 
     else if (xxx==1000) 
      cout<<"5"; 
     else if (xxx==10000) 
      throw "too big"; 
     else if (xxx==100000) 
      throw "too large"; 
     return 0; 
    } 
    catch (char const* exc) 
    { 
     cerr << exc << "\n"; 
    } 
} 

然而,是什么在这里增加了混乱的是,不像例外大多数其他语言,C++允许你丢东西的任何类型

让我们来仔细看看这条线的位置:

throw "too big"; 

"too big"是文字char const[8]类型。 C++允许你抛出这样的对象。由于它可以转换为char const*作为其第一个元素,所以您甚至可以将其捕获并将其他大小的字符串作为char const*

但这就是不常见的做法。您应该抛出直接或间接从std::exception派生的对象。

以下是使用<stdexcept>标题中的标准类std::runtime_error的示例。

(你的原代码没有使用来自<stdexcept>什么。你可以完全使用throw本身没有<stdexcept>。)

#include <iostream> 
#include <stdexcept> 
#include <exception> 

int main() 
{ 
    try 
    { 
     int xxx; 
     std::cout << "please enter xxx:"; 
     std::cin >> xxx; 
     if (xxx==1) 
      std::cout << "2"; 
     else if (xxx==10) 
      std::cout << "3"; 
     else if (xxx==100) 
      std::cout << "4"; 
     else if (xxx==1000) 
      std::cout << "5"; 
     else if (xxx==10000) 
      throw std::runtime_error("too big"); 
     else if (xxx == 100000) 
      throw std::runtime_error("too large"); 
     return 0; 
    } 
    catch (std::exception const& exc) 
    { 
     std::cerr << exc.what() << "\n"; 
    } 
}