Script raises HTTPError, but cannot catch - python

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)

Related

How to ignore the original exception and reraise a new exception [duplicate]

Consider
try:
import someProprietaryModule
except ImportError:
raise ImportError('It appears that <someProprietaryModule> is not installed...')
When run, if someProprietaryModule is not installed, one sees:
(traceback data)
ImportError: unknown module: someProprietaryModule
During handling of the above exception, another exception occurred:
(traceback data)
ImportError: It appears that <someProprietaryModule> is not installed...
Perhaps I don't want the "During handling of the above exception..." line (and the lines above it) to appear. I could do this:
_moduleInstalled = True
try:
import someProprietaryModule
except ImportError:
_moduleInstalled = False
if not _moduleInstalled:
raise ImportError('It appears that <someProprietaryModule> is not installed...')
But that feels like a bit of a hack. What else might I do?
In Python 3.3 and later raise ... from None may be used in this situation.
try:
import someProprietaryModule
except ImportError:
raise ImportError('It appears that <someProprietaryModule> is not installed...') from None
This has the desired results.
This can be done like this in Python 2.7 and Python 3:
try:
import someProprietaryModule
except ImportError as e:
raised_error = e
if isinstance(raised_error, ImportError):
raise ImportError('It appears that <someProprietaryModule> is not installed...')
You can try logging module as well
Original Answer:
Perhaps I don't want the "During handling of the above exception..." line (and the lines above it) to appear.
import logging
try:
import someProprietaryModule
except Exception as e:
if hasattr(e, 'message'):
logging.warning('python2')
logging.error(e.message)
else:
logging.warning('python3')
logging.error('It appears that <someProprietaryModule> is not installed...')
gives
WARNING:root:python3
ERROR:root:It appears that <someProprietaryModule> is not installed...
[Program finished]
Edit:
import logging
class MyExceptionType(Exception):
"""Base class for other exceptions"""
pass
try:
from someProprietaryModule import *
except Exception as e:
logging.warning('python3')
logging.exception("Failed to import <someProprietaryModule>. Is it installed?", exc_info=False)
raise MyExceptionType from e
logging.exception will emit the stacktrace alongside the localized error message, which makes it quite useful.
Casting an exception to a string to print it removes 90% of the useful information.
Silently suppressing exceptions is almost always an error and is most commonly a footgun.

handling exception from python gammu library

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']

Catching boto3 ClientError subclass

With code like the snippet below, we can catch AWS exceptions:
from aws_utils import make_session
session = make_session()
cf = session.resource("iam")
role = cf.Role("foo")
try:
role.load()
except Exception as e:
print(type(e))
raise e
The returned error is of type botocore.errorfactory.NoSuchEntityException. However, when I try to import this exception, I get this:
>>> import botocore.errorfactory.NoSuchEntityException
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named NoSuchEntityException
The best method I could find of catching this specific error is:
from botocore.exceptions import ClientError
session = make_session()
cf = session.resource("iam")
role = cf.Role("foo")
try:
role.load()
except ClientError as e:
if e.response["Error"]["Code"] == "NoSuchEntity":
# ignore the target exception
pass
else:
# this is not the exception we are looking for
raise e
But this seems very "hackish". Is there a way to directly import and catch specific subclasses of ClientError in boto3?
EDIT: Note that if you catch errors in the second way and print the type, it will be ClientError.
If you're using the client you can catch the exceptions like this:
import boto3
def exists(role_name):
client = boto3.client('iam')
try:
client.get_role(RoleName='foo')
return True
except client.exceptions.NoSuchEntityException:
return False
If you're using the resource you can catch the exceptions like this:
cf = session.resource("iam")
role = cf.Role("foo")
try:
role.load()
except cf.meta.client.exceptions.NoSuchEntityException:
# ignore the target exception
pass
This combines the earlier answer with the simple trick of using .meta.client to get from the higher-level resource to the lower-level client (source: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/clients.html#creating-clients).
try:
something
except client.exceptions.NoSuchEntityException:
something
This worked for me

Capturing beautifulsoup HTMLParseError exception

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)

Identify the exception to be used from the traceback

I want to catch an exception when user fails login due to wrong password .
So i make a function using imaplib .I enter a wrong password and get a traceback with error details.
Now my question is actually general.How do you identify the exception we have to mention in our "try and except" body from the error messages?
These is what I got->
>>> count("testarc31#gmail.com","Xbox#36")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
count("testarc31#gmail.com","Xbox#36")
File "E:\Arindam\py_progs\Mail Notifier\0.0.19\Mail.py", line 24, in count
obj.login(m,p)
File "C:\Python27\lib\imaplib.py", line 500, in login
raise self.error(dat[-1])
error: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
If i want to make a try and except,what will i mention in the exception part?
try:
login(mail,pass):
except ????:
something
Question :
1) What will be ???? here . Can it be deduced directly from the error report?
2) Is there a basic idea to identify what is the exception we have to use from each error we get ?
You want to use something like this:
try:
..code that might raise an exception...
except ExceptionType, e:
...do something...
In your case, that probably want this:
try:
login(mail,pass)
except imaplib.IMAP4.error, e:
print "Ouch -- an error from imaplib!"
To identify the type of an exception, you can look at its exception message. In this case it's just "error" -- unfortunately the module name is not included. You can get a better idea of exactly where it comes from by doing:
try:
login(mail,pass)
except Exception, e:
print type(e)

Categories