尝试捕获异常处理C++
Try catch exception handling C++
我刚刚开始使用try
和catch
块在C++中进行异常处理。我有一个包含一些数据的文本文件,我正在使用ifstream
和getline
读取此文件,如下所示,
ifstream file;
file.open("C:\Test.txt", ios::in);
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
我想知道如何在file.open
无法打开指定文件的情况下实现异常处理,因为它在给定路径中不存在,例如C:
中没有Test.txt
默认情况下,iostreams 不会引发异常。相反,他们设置了一些错误标志。您始终可以测试上一个操作是否成功,并将上下文转换为 bool:
ifstream file;
file.open("C:\Test.txt", ios::in);
if (!file) {
// do stuff when the file fails
} else {
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
}
您可以使用 exceptions
成员函数打开例外。我发现很多时候,这样做并没有多大帮助,因为你不能再做像while(getline(file, line))
这样的事情:这样的循环只会在异常的情况下退出。
ifstream file;
file.exceptions(std::ios::failbit);
// now any operation that sets the failbit error flag on file throws
try {
file.open("C:\Test.txt", ios::in);
} catch (std::ios_base::failure &fail) {
// opening the file failed! do your stuffs here
}
// disable exceptions again as we use the boolean conversion interface
file.exceptions(std::ios::goodbit);
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
大多数时候,我认为在iostreams上启用例外是不值得的。API 在关闭它们时效果更好。
IOstreams 为您提供了为各种状态位打开异常的选项。参考有一个非常清晰的例子,这正是您所要求的。
好吧,如果文件不存在,这完全取决于您要做什么。
当前的代码(假设这是main
(将退出进程。
但是,如果这是一个函数调用,那么您可能希望围绕对此函数的调用添加异常处理。
例如
try
{
OpenAndReadFile( std::string filename );
}
catch ( std::ifstream::failure e )
{
// do soemthing else
}
catch ( OtherException e )
{
}
catch ( ... )
{
// All others
}
这假设为ifstream
打开了异常引发。
相关文章:
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- 使用 stoi 功能进行异常处理
- 子系统中的异常处理:本机
- 与异常处理程序中的操作员<<不匹配
- 数组 C++ 上的异常处理程序
- 异常处理:如果用户输入不是三个特定字符之一
- C++ 异常处理错误输出
- 视觉 std::矢量无异常:警告 C4530:使用了C++异常处理程序,但未启用展开语义.指定 /EHsc
- C++交换机状态异常处理
- 在字符串类上的成员函数和out_of_range异常处理
- 奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来
- 执行视觉工作室异常处理模式
- 为什么隐式转换在异常处理中从派生到基?
- C++执行期间的类成员函数错误/异常处理
- C++ 中未处理的异常处理程序
- 用户定义的异常处理
- C :ScopeGuard vs返回支票和异常处理
- 异常处理期间的类型解析