Python OSError Exception
Example
An OSError occurs if a file cannot be opened:
f = open("missing.txt")
Try it Yourself »
Definition and Usage
The OSError exception occurs when the operating system reports an error, for example when a file does not exist, or when you do not have permission to use it.
OSError has more specific child classes, like FileNotFoundError and PermissionError. In the example, Python raises a FileNotFoundError, which is a kind of OSError.
Exception Handling
Example
Handling the OSError in a try...except statement:
try:
f = open("missing.txt")
except OSError:
print("The file could not be opened")
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.