Arvutiteaduse instituut
  1. Kursused
  2. 2024/25 sügis
  3. Programmeerimise alused (MTAT.03.236)
EN
Logi sisse

Programmeerimise alused 2024/25 sügis

  • 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 >

  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused