我应该使用std :: cerr和exit()而不是引发异常吗? [英] Should I use std::cerr and exit() instead of throwing an exception?

查看:217
本文介绍了我应该使用std :: cerr和exit()而不是引发异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++比较陌生,我只是想知道,抛出异常或编写std :: cerr和exit()之间的主要区别是什么?我知道,如果未捕获到异常,程序将退出。 std :: cerr是否有用例,还是应该始终抛出异常?还是我一般不应该使用std :: cerr?是否有一些最佳做法?

I'm relatively new to C++ and I am just wondering, what are the main differences between just throwing an exception or writing std::cerr and exit()? I know that if a exception isn't caught the program will exit. Are there any use cases for std::cerr or should I always throw exceptions? Or should I never use std::cerr in general? Are there some best practices for this?

throw std::runtime_error("runtime error msg");

OR

std::cerr << "cerr error msg";
exit(1);                      

两个版本都可以吗?

推荐答案

两者之间的主要区别是,您可以捕获和处理异常(通过 throw 引发)。此操作有两个优点:

The main difference between the two, is that you can catch and handle exception (raise with throw). There are two pros for this action:

A。您可以抛出异常并对其进行处理而不会导致程序崩溃。

A. You can throw an exception and handle it without crashing your program.

B。处理异常时,它们将自动调用对象的析构函数。例如:

B. When handling exception, they will automatically call the destructors of your objects. For example:

try {
    A a;
    throw runtime_error("A"); // Throw exception A
} catch (...) { // Catch exception A & Call a's object destructor.
    throw runtime_error("B"); // Throw exception B and crush (if no one else catch it).
}

您要使用掷球而不是 exit(1)选项。

有关更多详细信息,请参见:调用exit()时析构函数是否运行?& 在C ++中抛出异常后是否会调用析构函数?

For more details please see: Are destructors run when calling exit()? & Are destructors called after a throw in C++?

这篇关于我应该使用std :: cerr和exit()而不是引发异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆