2010-09-22 6 views
0

эй, я пытаюсь наследовать класс исключения и сделать новый класс NonExistingException: я написал следующий код в моем ч файла:Как использовать Исключения в программе на C++?

class NonExistingException : public exception 
{ 
public: 
    virtual const char* what() const throw() {return "Exception: could not find 
    Item";} 
}; 

в моем коде, прежде чем я посылаю что-то к функции I я пишу

try{ 
    func(); // func is a function inside another class 
} 
catch(NonExistingException& e) 
{ 
    cout<<e.what()<<endl; 
} 
catch (exception& e) 
{ 
    cout<<e.what()<<endl; 
} 

внутри func я бросаю исключение, но ничего не поймает. Заранее благодарим за помощь.

+0

Как вы бросали? Он должен выглядеть так: 'throw NonExistingVehicleException();' –

+3

Примечание: Лучше всего ловить по ссылке const. –

+0

Вы должны исключить исключение как «throw NonExistingException()», а не «throw new NonExistingException()». – avakar

ответ

5

Я хотел бы сделать это:

// Derive from std::runtime_error rather than std::exception 
// runtime_error's constructor can take a string as parameter 
// the standard's compliant version of std::exception can not 
// (though some compiler provide a non standard constructor). 
// 
class NonExistingVehicleException : public std::runtime_error 
{ 
    public: 
     NonExistingVehicleException() 
     :std::runtime_error("Exception: could not find Item") {} 
}; 

int main() 
{ 
    try 
    { 
     throw NonExistingVehicleException(); 
    } 
    // Prefer to catch by const reference. 
    catch(NonExistingVehicleException const& e) 
    { 
     std::cout << "NonExistingVehicleException: " << e.what() << std::endl; 
    } 
    // Try and catch all exceptions 
    catch(std::exception const& e) 
    { 
     std::cout << "std::exception: " << e.what() << std::endl; 
    } 
    // If you miss any then ... will catch anything left over. 
    catch(...) 
    { 
     std::cout << "Unknown exception: " << std::endl; 
     // Re-Throw this one. 
     // It was not handled so you want to make sure it is handled correctly by 
     // the OS. So just allow the exception to keep propagating. 
     throw; 

     // Note: I would probably re-throw any exceptions from main 
     //  That I did not explicitly handle and correct. 
    } 
} 
Смежные вопросы