终止并抛出类型未捕获异常

3

我正在尝试编写异常处理,以防找不到或打开txt文件。但是,编译器给出了“终止未捕获类型为char const *的异常”的错误提示。我不明白为什么无法看到catch消息“无法打开文件”。

try{

 ins.open(argv[1]);
 if ( !ins )
       throw "not";

} catch (char& e){
   cout << "File could not be opened";
   exit( 1 );
}

2
你正在抛出一个 const char*,但是你捕获的是一个 char&,类型不匹配。 - Caninonos
3个回答

3
""not"是正确的字符数组,你需要用catch (const char* e)来捕获它,但这真的是一个不好的处理方式..."
快速示例(来源:http://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception
{
  const char * what () const throw ()
  {
    return "C++ Exception";
  }
};

int main()
{
  try
  {
    throw MyException();
  }
  catch(MyException& e)
  {
    std::cout << "MyException caught" << std::endl;
    std::cout << e.what() << std::endl;
  }
  catch(std::exception& e)
  {
    //Other errors
  }
}

2
也许建议如何正确地使用标准异常类型? - BoBTFish
@BoBTFish 我确实有点懒,但你说得对 ;) - 56ka
噢,我对这个示例有很多问题... using namespace std;std::endl,将非const引用catch住。 - BoBTFish

1

虽然@56ka的回答是正确的,但为了使异常处理信息更加通用,您可以按照下面所示编写构造函数。

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

//Write your code here
struct MyException : public exception
{
    protected:
    const char *errorMsg;

    public:
    MyException (const char* str){
        errorMsg =  str;    
    }
    const char * what () const throw ()
    {
        return errorMsg;
    }
};

class Calculator
{
    public:

    int power(int n, int p){
        if ( n < 0 || p < 0){
            throw MyException("n and p should be non-negative");
        }
        return pow(n,p);
    }
};

int main()
{
    Calculator myCalculator=Calculator();
    try{
        int ans=myCalculator.power(2,-2);
        cout<<ans<<endl; 
    }
    catch(exception& e){
         cout<<e.what()<<endl;
    }

}

1
最好抛出std :: ios_base :: failure(C ++ 11)或其他派生自std :: exception的异常。 除非确实必须,否则不要编写自己的异常类。使用标准库定义的现有异常更加清晰。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接