Error Handling in File I/O

Unit 5 Β· Topic 5.7⏱ 8 min read❓ 5 MCQs

Introduction

Handle file errors by checking open success, state flags, and using exceptions if needed.

Definition

File Error Handling: check open success and stream state.

C++ Code Example

#include 
#include 
using namespace std;
int main(){
    ifstream f("missing.txt");
    if(!f){ cerr<<"Cannot open file\n"; return 1; }
    if(f.fail()){ cerr<<"Read error\n"; }
}

Important Questions

Short Questions

  1. How to detect open failure?
  2. How to handle read errors?
  3. What is cerr?
  4. Should we close on error?

Long Questions

  1. Explain file error handling.
  2. Discuss checking stream state.

MCQ Practice

1. Open failure detected by:

  • if(!f)
  • if(f)
  • always
  • never
Answer: if(!f).

2. cerr is:

  • Error output stream
  • Input stream
  • File stream
  • None
Answer: Error output stream.

3. On failure, should:

  • Handle and exit/close
  • Ignore
  • Continue
  • None
Answer: Handle and exit/close.

4. fail() indicates:

  • Logical failure
  • Success
  • EOF only
  • Good
Answer: Logical failure.

5. Good practice:

  • Check before use
  • Ignore errors
  • Assume success
  • None
Answer: Check before use.

Quick Revision

  • Check open success first.
  • Use cerr for errors.