Institute of Computer Science
  1. Courses
  2. 2025/26 fall
  3. Introduction to Programming (MTAT.03.236)
ET
Log in

Introduction to Programming 2025/26 fall

  • Home Page
  • Introduction
  • Expressions
  • Conditional Execution
  • Functions
  • Iterations
  • Strings
  • Files
  • Lists
  • Graphics?
< previousTable of Contents järgmine >

7.6 ERROR HANDLING IN FILE OPERATIONS

COMMON FILE ERRORS

The most common file error is the FileNotFoundError, which occurs when trying to open a file that does not exist.

Here's an example in Thonny of trying to open a file that does not exist.

However, important to note that if we'd specified a mode, such as r, even though the file didn't previously exist, it would be created.

Though, if our entered path was faulty in any other way, say we entered the name of the wrong directory when trying to access a certain file, then the result would also be a FileNotFoundeError. This would happen even if we'd specified the mode. See a Thonny example below.

USING TRY-EXCEPT BLOCKS TO CATCH EXCEPTIONS

Here is an example of handling a FileNotFoundError:


try:
    file = open('wrong_path.txt')
    content = file.read()
except FileNotFoundError:
    print("Sorry, the file does not exist.")
    exit()

In this example, if wrong_path.txt does not exist, Python raises a FileNotFoundError. The except block catches this exception, outputs feedback regarding the issue to the user and then gracefully exits the program.

< previousTable of Contents järgmine >

  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment