Menu
Coddy logo textTech

try-catch block

Lesson 17 of 23 in Coddy's C++ File Handling course.

A try block is created using the keyword try followed by curly braces. We use the try-block to enclose statements that might cause an exception and prevent the program from working properly.


When you open a file for reading or writing, several things can go wrong, such as the file not existing, permissions issues, or running out of disk space. By placing your file operations within a try block, you can anticipate these problems and prepare your program to handle them effectively.

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

In this program, if the file doesn't exist, the program will try to open it, but it will fail, in that case, the message File can't be found will be thrown


The catch block is used to define how your program should respond when an exception is thrown within a corresponding try block. In the context of file handling, this is crucial for maintaining the robustness and reliability of your application.

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

 This catch block captures the error message and outputs it, allowing your program to handle the error.

In this way, any error can be handled

challenge icon

Challenge

Easy

Try to open 3 files

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

If it's possible to open the files in that order throw the “error message” File opened successfully, otherwise, throw the error message Unable to open file which below you will catch and print out.

Try it yourself

#include <iostream>
#include <fstream>

using namespace std;

int main() 
{
    
    // Enter your code here
    
    return 0;
}

All lessons in C++ File Handling