When I handle an exception in python
try:
a = dict()
a[1]
except Exception as e:
print str(e)
It prints
1
I expect it to print
KeyError: 1
Is there a way to retrieve the default error message ?
Instead of this:
print str(e)
do this:
print(type(e).__name__ + ": " + str(e))
or just this:
print(type(e).__name__, e)
If you replace str(e) with repr(e) Python 2 will produce KeyError(1,) and Python 3 will produce KeyError(1)
This doesn't quite produce your desired output, but it may be close enough?
Related
I logically want to connect a user defined exception with general exception handling. Firstly, it should be checked whether the user defined exception is triggered. If it is not triggered, but another exception occurs, I want to print the exception information by get_exception_info().
I have the following code:
class TestException(Exception):
pass
def get_exception_info():
try:
exception_type, exception_value, exception_traceback = sys.exc_info()
file_name, line_number, procedure_name, line_code = traceback.extract_tb(exception_traceback)[-1] #this line is properly indented in my file
exception_info = ''.join('[Time Stamp]: '
+ str(time.strftime('%d-%m-%Y %I:%M:%S %p'))
+ '' + '[File Name]: ' + str(file_name) + ' '
+ '[Procedure Name]: ' + str(procedure_name) + ' '
+ '[Error Message]: ' + str(exception_value) + ' '
+ '[Error Type]: ' + str(exception_type) + ' '
+ '[Line Number]: ' + str(line_number) + ' '
+ '[Line Code]: ' + str(line_code))
return exception_info
except:
pass
def test_func(x):
try:
if x > 0:
raise TestException('wrong')
elif x < 0:
raise TestException('right')
else:
pass
except TestException as e:
print(e)
except Exception:
exception_info = get_exception_info()
print(exception_info)
finally:
pass
test_func(a)
Theoretically, this would cause an Exception and it should print out the result of get_exception_info(). However I just get "NameError: name 'a' is not defined.
What am I doing wrong? And, more importantly probably, is this the right way to archieve my goal?
Thank you!
The error indicates that the value a which you are passing into test_func() is not defined.
Add a line defining a, e.g.:
# ...
a = "hello"
test_func(a)
EDIT:
For your code to work, you also need to import time, traceback, and sys. I would also suggest not catching exceptions inside get_exception_info(), as this may hide exceptions that you actually want to see, i.e.:
import time
import traceback
import sys
class TestException(Exception):
pass
def get_exception_info():
exception_type, exception_value, exception_traceback = sys.exc_info()
file_name, line_number, procedure_name, line_code = traceback.extract_tb(exception_traceback)[-1]
exception_info = ' '.join([
'[Time Stamp]:',
time.strftime('%d-%m-%Y %I:%M:%S %p'),
'[File Name]:',
file_name,
'[Procedure Name]:',
procedure_name,
'[Error Message]:',
str(exception_value),
'[Error Type]:',
str(exception_type),
'[Line Number]:',
str(line_number),
'[Line Code]:',
line_code,
])
return exception_info
# ...
EDIT II:
It sounds like the question revolves around how to catch an undefined variable (a in this case).
In that case, I would suggest adding a try-except block around the function call, e.g.:
try:
test_func(a)
except Exception:
exception_info = get_exception_info()
print(exception_info)
When a is undefined, this will generate something along the lines of:
[Time Stamp]: 13-06-2021 10:44:31 AM [File Name]: /path/to/sf_exc.py [Procedure Name]: <module> [Error Message]: name 'a' is not defined [Error Type]: <class 'NameError'> [Line Number]: 76 [Line Code]: test_func(a)
Comment
As a general remark, instead of manually formatting the error message, I would use Python's logging module which is powerful and gives a lot of flexibility when it comes to formatting different types of messages, using a custom Formatter. In particular, Formatter comes with methods that can be customised to treat exceptions and stack information.
I'm trying to execute a python script from Linux but I'm keep getting this error on the except line. Can someone figure this out?
$ python pygeo_ip.py
def search(self):
message = ''
result_count = 0
gip = pygeoip.GeoIP('GeoLIteCity.dat')
ip = self.ip_textbox.text()
try:
ip = socket.gethostbyname(str(ip))
message = "Host: %s Is Currently Available" % (str(ip))
except socket.error, e:
message = "Host: %s Is Currently Unavailable" % (key, val)
result_count += 1
msg_box("SeArCh CoMpLeTe", "%d REsults Were Found For %s"
% (result_count, str(ip))
except Exception, e: <------- Error
msg_box("", str(e))
msg_box("Search Complete", "No Results Were Found For %s" % (str(ip))
return
Error:
File "pygeo_ip.py", line 142
except Exception, e:
^
SyntaxError: invalid syntax
Pretty sure (without having tested anything) your problem is having missed the last close bracket
Line should read:
msg_box("SeArCh CoMpLeTe", "%d REsults Were Found For %s" % (result_count, str(ip)) )
I wrote a hiscore checker for a game that I play, basically you enter a list of usernames into the .txt file & it outputs the results in found.txt.
However if the page responds a 404 it throws an error instead of returning output as " 0 " & continuing with the list.
Example of script,
#!/usr/bin/python
import urllib2
def get_total(username):
try:
req = urllib2.Request('http://services.runescape.com/m=hiscore/index_lite.ws?player=' + username)
res = urllib2.urlopen(req).read()
parts = res.split(',')
return parts[1]
except urllib2.HTTPError, e:
if e.code == 404:
return "0"
except:
return "err"
filename = "check.txt"
accs = []
handler = open(filename)
for entry in handler.read().split('\n'):
if "No Displayname" not in entry:
accs.append(entry)
handler.close()
for account in accs:
display_name = account.split(':')[len(account.split(':')) - 1]
total = get_total(display_name)
if "err" not in total:
rStr = account + ' - ' + total
handler = open('tried.txt', 'a')
handler.write(rStr + '\n')
handler.close()
if total != "0" and total != "49":
handler = open('found.txt', 'a')
handler.write(rStr + '\n')
handler.close()
print rStr
else:
print "Error searching"
accs.append(account)
print "Done"
HTTPERROR exception that doesn't seem to be working,
except urllib2.HTTPError, e:
if e.code == 404:
return "0"
except:
return "err"
Error response shown below.
Now I understand the error shown doesn't seem to be related to a response of 404, however this only occurs with users that return a 404 response from the request, any other request works fine. So I can assume the issue is within the 404 response exception.
I believe the issue may lay in the fact that the 404 is a custom page which you get redirected too?
so the original page is " example.com/index.php " but the 404 is " example.com/error.php "?
Not sure how to fix.
For testing purposes, format to use is,
ID:USER:DISPLAY
which is placed into check.txt
It seems that total can end up being None. In that case you can't check that it has 'err' in it. To fix the crash, try changing that line to:
if total is not None and "err" not in total:
To be more specific, get_total is returning None, which means that either
parts[1] is None or
except urllib2.HTTPError, e: is executed but e.code is not 404.
In the latter case None is returned as the exception is caught but you're only dealing with the very specific 404 case and ignoring other cases.
This is part of my code in python. I want to check the error message and if HTTPError() then I want to add the host to the file ok.txt. But it doesn't work. what is the problem here?
except urllib2.URLError, e:
print '%-15s\t%15r' % (url.strip(), e)
if e == 'HTTPError()':
OK.write('%-15s' % (url.strip()) + '\n')
OK.flush()
When I run whole script the output is something like this:
http://a.com HTTPError()
http://b.com URLError(timeout('timed out',),)
http://c.com URLError(timeout('timed out',),)
http://d.com URLError(error(111, 'Connection refused'),)
http://e.com 200
Use isinstance() to check whether or not your error is of type HTTPError:
except urllib2.URLError as e: # use the "as e" instead of the old style comma delimitation.
print '%-15s\t%15r' % (url.strip(), e)
if isinstance(e, HTTPError):
OK.write('%-15s' % (url.strip()) + '\n')
OK.flush()
I recently switched from urlib2 to requests and I'm not sure how to deal with exceptions. What is best practice? My current code looks like this, but is not doing any good:
try:
response = requests.get(url)
except requests.ConnectionError , e:
logging.error('ConnectionError = ' + str(e.code))
return False
except requests.HTTPError , e:
logging.error('HTTPError = ' + str(e.reason))
return False
except requests.Timeout, e:
logging.error('Timeout')
return False
except requests.TooManyRedirects:
logging.error('TooManyRedirects')
return False
except Exception:
import traceback
logging.error('generic exception: ' + traceback.format_exc())
return False
Since it looks bad as a comment, have you tried:
try:
# some code
except Exception as e:
print e