I am getting the exception from Beutifulsoup HTMLParseError: expected name token at u'<![0Y', at line 1371, column 24 - arising because the html I am reading in is malformed.
How do I capture this error - I have tried
try:
...
except HTMLParseError:
pass
but that results in the error NameError: global name 'HTMLParseError' is not defined
I have also tried except BeautifulSoup.HTMLParseError: but that then gives the error AttributeError: type object 'BeautifulSoup' has no attribute 'HTMLParseError'
More broadly, when i get an custom error from a package i am using, how is it possible to "work out" what the exception needs to be to handle it?
BeautifulSoup is raising HTMLParseError from the HTMLParser library. Try importing the error from that library before using it in your try/except:
from HTMLParser import HTMLParseError
try:
# error happens
except HTMLParseError:
pass
More info on the HTMLParse library is here.
See where error is raised in BeautifulSoup source code here.
have you tried catch NameError exception?
if you can't catch it try this:
try:
# error happens
except Exception as e:
# log the exception here
print(e)
Related
I'm using python gammu library for sending sms. Sometimes something is wrong and I would like to handle exception. Descritpion of Exceptions is here: https://wammu.eu/docs/manual/python/exceptions.html#module-gammu.exception
I have a problem with getting and returning errors from such situations. I've printed:
print(sys.exc_info())
It has result:
(<class 'gammu.ERR_UNKNOWN'>, ERR_UNKNOWN({'Text': 'Nieznany błąd.', 'Where': 'SendSMS', 'Code': 27}), <traceback object at 0x740a6cd8>)
If i assign:
error_obj = sys.exc_info()
How can I get from it: Text, Code, and type ERROR(here is ERR_UKNOWN)?
I will grateful for help.
cls, exception, _ = sys.exc_info()
text = exception['Text'] # or exception.Text ?
code = exception['Code'] # or exception.Code ?
print(cls, text, code)
Also take a look at traceback module:
import traceback
try:
1/0
except ArithmeticError as e:
traceback.print_exc()
You should be able to use the args on the exception to get to the Text:
print(error_obj.args)
error_obj.args[0]['Text']
I am working with some Python/Django code that I inherited. In it there is a DB call surrounded by a try block, with an "except Exception ex" statement to catch all exceptions. I want to be more selective, and catch only the exception type that I anticipate. By examining the Exception object that is caught, I can tell that it's of type "DatabaseError".
The comments in my code below show the many things I have tried, based on Googling the question and searching here, along with the errors that Python gives me when I try them. Most frustrating is that I've found plenty of examples on the web of code the people say works, that looks just like what I'm trying. But the code samples I find generally don't include the "import" lines.
I suspect I need to import something more, but I can't figure out what.
import cx_Oracle
## import cx_Oracle.DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
## from cx_Oracle import DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
. . .
connection = connections['ims_db']
sqlUpdateQuery = "SELECT * FROM LOCKING WHERE IDENT={0} AND KEY_ID='SL_KEY' FOR UPDATE NOWAIT".format(self.serviceUid)
cursor = connection.cursor()
try:
cursor.execute(sqlUpdateQuery)
# this gets the error "Undefined variable 'Database'"
## except Database.DatabaseError as dbe3:
# this gets the error "Undefined variable 'Oracle'"
## except Oracle.DatabaseError as dbe2:
# this gets the error "Module 'cx_Oracle' has no 'DatabaseError' member"
## except cx_Oracle.DatabaseError as dbe:
# this gets the error "Undefined variable 'DatabaseError'"
## except DatabaseError as dbe:
# this gets the error "Catching an exception which doesn't inherit from BaseException: cx_Oracle"
## except cx_Oracle as dbe:
# this gets the error "Module cx_Oracle has no '_error' member"
## except cx_Oracle._Error as dbe:
except Exception as ex:
# This gets the error "Module cx_Oracle has no 'DatabaseError' member"
## if isinstance(ex, cx_Oracle.DatabaseError) :
# This gets the error "Undefined variable 'DatabaseError'"
## if isinstance(ex, DatabaseError) :
className = type(ex).__name__
# This logs "... class = DatabaseError ..."
log.error("Exception (class = {1}) while locking service {0}".format(self.serviceUid, className))
args = ex.args
arg0=args[0]
# arg0ClassName is "_Error"
arg0ClassName = type(arg0).__name__
code = arg0.code
# codeClassName is "int"
codeClassName = type(code).__name__
msg = "Exception, code = {0}".format(code)
log.debug(msg)
raise
The correct syntax is as follows:
try:
cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
error, = e.args
print("CONTEXT:", error.context)
print("MESSAGE:", error.message)
You can see that syntax in a few of the samples (like TypeHandlers.py) that you can find here: https://github.com/oracle/python-cx_Oracle/tree/master/samples.
Try running the samples and working with them to see if you can resolve your issue. If not, please create an issue containing a complete runnable sample here: https://github.com/oracle/python-cx_Oracle/issues.
I have an error which I have a little difficulty understanding. I have a script which uses biopython to query a database. Sometimes, biopython can't find what we're looking for, and an HTTPError is thrown. I cannot, however catch the HTTPError, as I get the following error message:
HTTPError: HTTP Error 404: Not Found
During handling of the above exception, another exception occurred:
NameError Traceback (most recent call
last) in ()
51 UniProt = text[index+9:index+15]
52 uniprot_IDs[bigg_ID] = UniProt
---> 53 except HTTPError:
54 if err.code == '404':
55 uniprot_IDs[biGG_ID] = None
NameError: name 'HTTPError' is not defined
How can an error which is not defined be thrown in the first place? What am I missing?
This is the relevant code:
from Bio.KEGG import REST, Enzyme
from DataTreatment import openJson, write
...
try:
ec_number = some_string
text = REST.kegg_get('ec:'+ec_number).read()
...
except HTTPError:
if err.code == '404':
a_dict[a_key] = None
You need to import the HTTPError class. If you already imported, then make sure you got the right one. You can try to catch with a generic Exception and use type(ex) to find out which it is and import the correct type.
You need to import the HTTPError-class, try this;
In the top of your code, add
from urllib.error import HTTPError
Source: Entrez._HTTPError vs. Entrez.HTTPError (via Entrez.efetch)
I need to catch a specific OperationalError exception. The exception text uses the error-code 2006. The library defines the error-codes at MySQLdb.constants.CR.SERVER_GONE_ERROR = 2006.
How do you get the error-code from the exception?
When I check the MySQLdb._mysql_exceptions, there is a definition of the OperationalError exception but it has no constructor or description of how to access the exception error code.
You can catch the error number like the following:
try:
# Adding field 'Bug.bize_size_tag_name'
db.add_column('search_bug', 'bize_size_tag_name', orm['search.bug:bize_size_tag_name'])
except MySQLdb.OperationalError, errorCode:
if errorCode[0] == 1060:
pass
else:
raise
Reference: https://www.programcreek.com/python/example/2584/MySQLdb.OperationalError
For a newbie exercise , I am trying to find the meta tag in a html file and extract the generator so I did like this :
Version = soup.find("meta", {"name":"generator"})['content']
and since I had this error :
TypeError: 'NoneType' object has no attribute '__getitem__'
I was thinking that working with exception would correct it, so I wrote :
try: Version = soup.find("meta", {"name":"generator"})['content']
except NameError,TypeError:
print "Not found"
and what I got is the same error.
What should I do then ?
The soup.find() method did not find a matching tag, and returned None.
The [...] item access syntax looks for a __getitem__ method, which is the source of the AttributeError here:
>>> None[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object has no attribute '__getitem__'
Test for None explicitly:
Version = soup.find("meta", {"name":"generator"})
if Version is not None:
Version = Version['content']
else:
print "Not found"
Your exception handling would work too, provided you use parenthesis to group the exceptions:
try:
Version = soup.find("meta", {"name":"generator"})['content']
except (NameError, TypeError):
print "Not found"
Without parenthesis you are telling Python to catch NameError exceptions and assign the resulting exception object to the local name TypeError. This except Exception, name: syntax has been deprecated because it can lead to exactly your situation, where you think you are catching two exceptions.
However, your code here should not throw a NameError exception; that'd be a separate problem better solved by instantiating your variables properly; the following would work just as well here:
try:
Version = soup.find("meta", {"name":"generator"})['content']
except TypeError:
# No such meta tag found.
print "Not found"
Try this:
content = None
Version = soup.find("meta", {"name":"generator"})
if Version:
content = Version.get('content')
#or even
#Version = Version.get('content')
else:
print "Not found"
The issue is, soup.find returns a None if match was not found, and extracting data out of None results in error.