【发布时间】:2020-08-26 18:10:49
【问题描述】:
也许这是一个愚蠢的问题,但我不明白为什么我可以在前一段代码中捕获异常,而在后者中却不能。
第一段代码:
int main() {
try {
throw std::logic_error("Error");
sf::RenderWindow window(sf::VideoMode(800, 600), "Test", sf::Style::Default);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color::Black);
window.display();
}
}
catch(std::logic_error& l){
std::cerr<<l.what()<<std::endl;
exit(42);
}
return 0;
}
第二段代码:
int main() {
try {
sf::RenderWindow window(sf::VideoMode(800, 600), "Test", sf::Style::Default);
throw std::logic_error("Error");
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color::Black);
window.display();
}
}
catch(std::logic_error& l){
std::cerr<<l.what()<<std::endl;
exit(42);
}
return 0;
}
【问题讨论】:
-
仅供参考,通常最好通过
const引用而不是非常量来捕获异常,例如:catch(const std::logic_error& l)
标签: c++ exception sfml uncaught-exception