Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising builtin exception with default message in python

Tags:

I'm trying to implement a method that returns an error whenever a certain directory does not exist.

Rather than doing raise OSError("Directory does not exist."), however, I want to use the builtint error message from OSError: OSError: [Errno 2] No such file or directory:. This is because I am raising the exception in the beginning of the method call, rather than later (which would invoke the same message from python, without any necessary raise).

Any pointers? (other than manually doing OSError("[Errno 2] No such file or directory: "))

like image 298
bow Avatar asked Jan 23 '12 20:01

bow


People also ask

How do you raise an exception in a message in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

How does Python handle default exceptions?

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. We can thus choose what operations to perform once we have caught the exception.

How does a built-in exception get raised?

This exception is derived from RuntimeError . It is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit() ) is exceeded. New in version 3.5: Previously, a plain RuntimeError was raised.


2 Answers

import os  try:     open('foo') except IOError as err:     print(err)     print(err.args)     print(err.filename)     

produces

[Errno 2] No such file or directory: 'foo' (2, 'No such file or directory') foo 

So, to generate an OSError with a similar message use

raise OSError(2, 'No such file or directory', 'foo') 
like image 112
unutbu Avatar answered Oct 14 '22 13:10

unutbu


To get the error message for a given error code, you might want to use os.strerror:

>>> os.strerror(2) 'No such file or directory' 

Also, you might want to use errno module to use the standard abbreviations for those errors:

>>> errno.ENOENT 2 >>> os.strerror(errno.ENOENT) 'No such file or directory' 
like image 38
jcollado Avatar answered Oct 14 '22 11:10

jcollado