I need to obtain the error number from an error that has occurred in Python.
Ex; When trying to transfer a directory via the Paramiko package, an error is caught with this piece of code:
try:
sftp.put(local_path,target_path)
except (IOError,OSError),errno:
print "Error:",errno
For which I get the output,
Error: [Errno 21] Is a directory
I want to utilize the error number to go into some more code to transfer the directory and the directory contents.
message (at least in Python 2.7. 12). If you want to capture the error message, use str(e) , as in the other answers.
An Error might indicate critical problems that a reasonable application should not try to catch, while an Exception might indicate conditions that an application should try to catch. Errors are a form of an unchecked exception and are irrecoverable like an OutOfMemoryError , which a programmer should not try to handle.
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.
Handling ValueError Exception Here is a simple example to handle ValueError exception using try-except block. import math x = int(input('Please enter a positive number:\n')) try: print(f'Square Root of {x} is {math. sqrt(x)}') except ValueError as ve: print(f'You entered {x}, which is not a positive number.
Thanks for clarifying your question.
Most Exception
s in Python don't have "error numbers". One exception (no pun intended) are HTTPError
exceptions, for example:
import urllib2
try:
page = urllib2.urlopen("some url")
except urllib2.HTTPError, err:
if err.code == 404:
print "Page not found!"
else:
...
Another exception (as noted by bobince) are EnvironmentError
s:
import os
try:
f=open("hello")
except IOError, err:
print err
print err.errno
print err.strerror
print err.filename
outputs
[Errno 2] No such file or directory: 'hello'
2
No such file or directory
hello
If you're talking about errno.h
error numbers, you can get them from the errno
property on the exception object, but only on EnvironmentError
(which includes OSError
, IOError
and WindowsError
).
Specifically on WindowsError
you'll also get a winerror
property with a Windows-specific error number. (You don't often see one of these though, as Python uses the Win32 API directly relatively rarely.)
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