Menu
CoddyTech

try-catch 语句块

Coddy C++ 文件处理 课程的第 17 课,共 23 课。

使用关键字 try 后跟花括号即可创建 try 块。我们用 try 块包住可能导致异常、使程序无法正常运行的语句。


打开文件进行读取或写入时,可能会出现各种问题,例如文件不存在、权限不足或磁盘空间不足。将文件操作放在 try 块中,你就可以预料到这些问题,并让程序做好准备,以便妥善处理它们。

string error_message = "File can't be found"
ifstream file;
try {
	file.open("example.txt");
	if(!file.is_open())
		throw s;
	}

在这个程序中,如果文件不存在,程序会尝试打开它,但会失败。在这种情况下,会抛出消息 File can't be found will be thrown


catch 块用于定义当对应的 try 块中抛出异常时,程序应如何响应。在文件处理方面,这对于保持应用程序的健壮性和可靠性至关重要。

string error_message = "File not found"
ifstream file;
try {
	file.open("example.txt");
	if(!file.is_open())
		throw error_message;
} catch(string msg) {
	cerr << msg << endl;
Output:
File not found

 这个 catch 块会捕获错误消息并将其输出,让程序能够处理错误。

这样就可以处理任何错误。

challenge icon

挑战

简单

尝试打开 3 个文件

  • code.txt
  • messages.txt
  • python.txt

如果能按此顺序打开这些文件,就抛出“错误消息”File opened successfully;否则,抛出错误消息Unable to open file,然后你会捕获并打印该消息。

亲手试试

#include <iostream>
#include <fstream>

using namespace std;

int main() 
{
    
    // 在这里输入你的代码
    
    return 0;
}

C++ 文件处理中的所有课

自己练习: C++ 在线编译器