I'm trying the write exception an handling in case a txt file could not be found and open. I'm receiving "terminating with uncaught exception of type char const*" from the compiler. I don't understand why I cannot see the catch message "File could not be opened"
try{
ins.open(argv[1]);
if ( !ins )
throw "not";
} catch (char& e){
cout << "File could not be opened";
exit( 1 );
}
答案 0 :(得分:3)
"not"
is rightly a char array, you have to catch it with catch (const char* e)
but this is really a bad way to proceed...
Quick example (source: 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
}
}
答案 1 :(得分: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;
}
}
答案 2 :(得分:0)
Better to throw std::ios_base::failure (C++11) or something else that derives from std::exception. Don't write your own exception classes unless you really have to. It's cleaner to use the existing exceptions defined by the standard library.