I'm importing a module which raises the following error in some conditions:
RuntimeError: pyparted requires root access
I know that I can just check for root access before the import, but I'd like to know how to catch this spesific kind of error via a try/except statement for future reference. Is there any way to differentiate between this RuntimeError and others that might be raised?
You can check attributes of the exception to differentiate from other possible RuntimeError exceptions. For example, re-raise the error if it does not match a predefined message text.
try:
import pypatred
except RuntimeError,e:
if e.message == 'RuntimeError: pyparted requires root access':
return 'pyparted - no root access'
raise
Of course, direct text comparison is just an example, you could search for included substrings or regular expressions.
It is worth noting that the .message attribute of exceptions is deprecated starting with Python 2.6. You can find the text in .args, usually args[0].
... For 2.6, the message attribute is being deprecated in favor of the args attribute.
I know that I can just check for root access before the import, but I'd like to know how to catch this spesific kind of error via a try/except statement for future reference. Is there any way to differentiate between this RuntimeError and others that might be raised?
If the error is caused by a specific condition, then I think the easiest way to catch the error is to test for the condition, and you can raise a more specific error yourself. After all the 'error' exists before the error is thrown, since in this case its a problem with the environment.
I agree with those above - text matching on an error is kind of a terrifying prospect.
try:
import pyparted
except RuntimeError:
print('RuntimeError is raised')
raise
more on exception handling in tutorial.
This situation should produce ImportError in my opinion. And you can do it yourself:
try:
import pyparted
except RuntimeError as e:
raise ImportError(e)
RuntimeError Raised when an error is detected that doesn’t fall in any of the other categories
def foo():
try:
foo()
except RuntimeError, e:
print e
print " Runtime Error occurred due to exceeded maximum recursion depth "
That is how we will catch the RuntimeError caused by the exceeded recursion limit in python
And if you want to call your function over the recursion limit you can do the following
import sys
def foo():
try:
foo()
except RuntimeError, e:
sys.setrecursionlimit(1200)
foo()
But always it is highly not recommended to change the recursion limit,
but very small changes in the recursion limit are allowed
Yes.
try:
import module
except RuntimeError:
pass
imports are interpreted as any other statement, they are not special. You could do an
if condition:
import module
try:
import ...
except RuntimeError:
# Do something
Related
I'm importing some Python modules and they will raise exception with calls like raise TypeError(xyz). And now I want to change the line number of the reported exceptions if there is any.
I couldn't find the right solution on the site for my case, the one I found all required the raise() to be in a try and except block. With the warnings module I can do warnings.formatwarning to customize its format. Can I do the same with exception?
I have a python file (app.py) which makes a call to a function as follows:
answer = fn1()
The fn1() is actually written in C++ and I've built a wrapper so that I can use it in Python.
The fn1() can either return a valid result, or it may sometimes fail and terminate. Now the issue is that at the times when fn1() fails and aborts, the calling file (i.e. app.py) also terminates and does not go forward to the error handling part.
I would like the calling file to move to my error handling part (i.e. 'except' and 'finally') if fn1() aborts and dumps core. Is there any way to achieve this?
From the OP:
The C++ file that I have built wrapper around aborts in case of exception and dumps core. Python error code is not executed
This was not evident in your question. To catch this sort of error, you can use the signal.signal function in the python standard library (relevant SO answer).
import signal
def sig_handler(signum, frame):
print("segfault")
signal.signal(signal.SIGSEGV, sig_handler)
answer = fn1()
You basically wrote the answer in your question. Use a try except finally block. Refer also to the Python3 documentation on error handling
try:
answer = fn1()
except Exception: # You can use an exception more specific to your failing code.
# do stuff
finally:
# do stuff
What you need to do is to catch the exception in your C++ function and then convert it to a python exception and return that to the python code.
So, we had instance in the past where code were broken in IOT devices because of syntax errors.
While there is exception handling in the code. I wanted to create a script to check and make sure that the codes compiles and run without syntax error, else the script replace the broken code by an earlier version.
I tried this
from delta_script import get_update
def test_function():
try:
get_update()
except SyntaxError as syntaxError:
replace_script("utility.py", syntaxError)
except Exception as ignored:
pass
However the problem it when it hit a SyntaxError, it just throw it on the screen and replace_script
because the exception happens on delta_script.py from which get_update() was imported.
So what's the solution in this case?
I have also another function
def compile():
try:
for file in compile_list:
py_compile.compile(file)
except Exception as exception:
script_heal(file, exception)
however in this one, it never report any exception, because I go and introduce syntaxError and the code still compile without reporting an error
Any one could help me figure out a better way to solve those two problems?
thanks,
SyntaxErrors occur at compile time, not run time, so you generally can't catch them. There are exceptions, involving run time compilation using eval/exec, but in general, except SyntaxError: is nonsensical; something goes wrong compiling the code before it can run the code that sets up the try/except to catch the error.
The solution is to not write syntactically invalid code, or if you must write it (e.g. to allow newer Python syntax only when supported) to evaluate strings of said code dynamically with eval (often wrapping compile if you need something more complicated than a single expression) or exec.
I am currently using Python 2 on a project that needs a Python 3 built-in exception: FileNotFoundError. How do I do it?
You can of course define any exceptions you want.
But they're not going to do you any good. The whole point of FileNotFoundError is that any Python operation that runs into a file-not-found error will raise that exception. Just defining your own exception won't make that true. All you're going to get is an OSError (or IOError, depending on 2.x version) with an appropriate errno value. If you try to handle a custom FileNotFoundError, your handler will never get called.
So, what you really want is (for example):
try:
f = open(path)
except OSError as e:
if e.errno == errno.ENOENT:
# do your FileNotFoundError code here
else:
raise
You could use IOError instead:
Raised when an I/O operation (such as a print statement, the built-in open() function or a method of a file object) fails for an I/O-related reason, e.g., “file not found” or “disk full”.
This class is derived from EnvironmentError. See the discussion above for more information on exception instance attributes.
Changed in version 2.6: Changed socket.error to use this as a base class.
You can simply create the FileNotFoundError exception yourself:
class FileNotFoundError(OSError):
pass
This new exception class inherits from OSError just like the one in Python 3.x.
Here is a reference on User-defined Exceptions in Python.
Short answer: Just use EnvironmentError and check err.errno == errno.ENOENT for either Python 2 or Python 3.
Long answer:
As other answers have mentioned, FileNotFoundError is new to Python 3.
Python 2 used OSError (or IOError, depending on 2.x version). OSError and IOError both inherit from EnvironmentError.
In Python 3, EnvironmentError is aliased to OSError. FileNotFoundError inherits from OSError, which means that FileNotFoundError can be caught with EnvironmentError, and it shares the same interface as OSError and IOError.
So, good news! This means that there is a relatively easy way to make your project compatible with both Python 2 and Python 3 at the same time: leave FileNotFoundError out of it, and just catch EnvironmentError.
# Works for Python 2. Also works for Python 3.
import errno
try:
open("fake.file", 'r')
except EnvironmentError as err:
if err.errno == errno.ENOENT: # ENOENT -> "no entity" -> "file not found"
print("Caught 'file not found' exception")
else:
raise
I'm writing some code to manipulate the Windows clipboard. The first thing I do is to try and open the clipboard with OpenClipboard() function from the Windows API:
if OpenClipboard(None):
# Access the clipboard here
else:
# Handle failure
This function can fail. So if it does, I would like to raise an exception. My question is, which of the standard Python exceptions should I raise? I'm thinking WindowsError would be the right one, but not sure. Could someone please give me a suggestion?
It is better to avoid raising standard exceptions directly. Create your own exception class, inherit it from the most appropriate one (WindowsError is ok) and raise it. This way you'll avoid confusion between your own errors and system errors.
Raise the windows error and give it some extra infomation, for example
raise WindowsError("Clipboard can't be opened")
Then when its being debugged they can tell what your windows error means rather than just a random windowserror over nothing.
WindowsError seems a reasonable choice, and it will record extra error information for you. From the docs:
exception WindowsError
Raised when a Windows-specific error occurs or when the error number does not correspond to an errno value. The winerror and strerror values are created from the return values of the GetLastError() and FormatMessage() functions from the Windows Platform API. The errno value maps the winerror value to corresponding errno.h values. ...