I have some code that potentially could raise an OSError
based on the user's input. More specifically, it could raise OSError: [WinError123]
. The problem I'm facing is that my try except block checks for OSError
which is way too broad of an exception.
I've looked at this question and this question however, it's unclear to me how errno
works. I've also looked at the errno
documentation but it is unclear to me how it relates to the specific errors within OSError
.
How do I catch a specific OSError
namely, WinError 123
?
Also if you could explain to me what libraries you utilized / how you did it / the thought process of your solution would be wonderful!
OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as “file not found” or “disk full”. Below is an example of OSError: Python.
Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
The Python try… except statement runs the code under the “try” statement. If this code does not execute successfully, the program will stop at the line that caused the error and the “except” code will run. The try block allows you to test a block of code for errors.
exception BaseException This is the base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes. For, user-defined classes, Exception is used. This class is responsible for creating a string representation of the exception using str() using the arguments passed.
Can you not do something like:
try:
my_function()
except OSError as e:
if e.args[0] != 123:
raise
print("Deal with the 123 error here")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With