Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for a certain type of OSError in a try except block?

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!

like image 611
Dzhao Avatar asked Mar 10 '16 18:03

Dzhao


People also ask

What is an OSError?

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.

How do you catch exceptions in 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.

How can the try except statements handle errors in Python?

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.

Which of the following built-in exceptions is the root class for all exceptions?

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.


1 Answers

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")
like image 62
Goodies Avatar answered Oct 27 '22 00:10

Goodies