在c ++中使用异常处理的一个小问题

时间:2011-07-01 09:46:32

标签: c++ visual-c++ exception-handling

下面给出的简单异常程序给出了Unhandled Exception“Microsoft C ++异常:int在内存位置0x0012fe94 ..”。返回函数excep()后,我立即收到此错误。 请有人知道为什么会出现这个错误。如果解释/分析了此代码中的所有可能错误,也会有所帮助。我正在学习编码更好。

我正在使用Visual C ++ 2005.

#include <iostream>
using namespace std;

int main ()
{
   int excep(int);

   throw excep(20);

   return 0;
}

int excep(int e)
{

    cout << "An exception occurred. Exception Nr. " << e << endl;
    return 0;

}

3 个答案:

答案 0 :(得分:3)

如果您尝试学习异常抛出/处理,则代码中包含错误。 函数excep必须处理抛出不会被抛出的对象。 您的代码必须按如下方式重写:

using namespace std;
int excep(int e) 
{ 
       cout << "An exception occurred. Exception Nr. " << e << endl; 
       return 0;
}
int main () 
{ 
     int excep(int);
     try
     { // <--------- Begin of try block. required part of the exception handling
         throw 20;
     }
     catch (const int &errCode) // <------- we are catching only ints
     {
             excep(errCode); // Function that handles exception
     }

     return 0; 
}  

设计不抛出int变量,但继承std :: exception的类型是好的设计。但这是使用知识的更高级的例外

答案 1 :(得分:3)

您期望发生什么?

您调用一个打印出“发生异常”的函数,再加上其他文本,然后将结果值作为异常抛出,这是您永远不会捕获的,因此程序报告的内容比未捕获的异常更多。这是真的,因为这正是你刚才所做的。

异常中的全部内容是,当您抛出异常时,它将通过程序传播出去,直到它被处理,或者它到达顶层并终止程序。您没有处理异常,因此终止程序。

如果要处理异常,则需要将抛出代码包装在try块中,然后包含catch,如下所示:

try {
    throw excep(20);
}
catch (int ex) {
   // do something about the exception
}

答案 2 :(得分:1)

在第

throw excep(20);
首先调用

excep(20),然后抛出其返回值,即抛出一个整数。它大致相当于:

const int i = excep(20);
throw i;

让您了解exception-snytax的外观:

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

int main ()
{
   try {
       // do something
       throw std::runtime_error("test");
   } catch (const std::exception &e) {
       std::cout << "exception: " << e.what() << std::endl;
   }
}

在practive中:从不抛出任何非std::exception派生的内容。

建议读物: