Raising user defined exception when connecting to sqlite - python

Let's say that I want to connect to database but getting an error on connect. In most of examples what I found people catch basic Error exception. But it also will catch any other mistake. So, the question is, what should I do to raise different user defined exceptions? In other words, how to throw user defined exception instead of predefined exception?

Like this:
class MySpecificException(Exception):
print('Handle exception here:')
try:
1/0
except ZeroDivisionError as e:
print('error text')
raise MySpecificException('SpecificException')

Related

Unit test: test not failing if using try-except

I am trying to execute post-failure operations; so I can gather info on the state of the system only if it fail.
So far, I did not find a solution that works. I did try to add a try-except and this works; but then the output of my test run is "success", which is totally wrong.
try:
self.assertFalse(x>1, "the test failed")
except Exception as e:
print(e)
# do other post failure actions
Since the exception is caught, I assume that the unit test class won't be involved in reporting the error, and this end up with the test not failing.
How do I "escalate" the failure at the same time to both the except section and the Unit test class?
You can re-raise the exception once you caught and recorded it:
try:
self.assertFalse(x>1, "the test failed")
except Exception as e:
print(e)
# do other post failure actions
raise
Note that you may and should be more specific about the error you are catching - in this case, you are looking for catching the AssertionError exception instead of the generic Exception.

Raise exception for error logs

I'm using a library that is logging an error. But I'd like it to raise an exception instead.
Is there quick way to have an exception raised instead of just an error being logged?
The library I'm using is cssutils, but for simplicity, suppose my code looks like:
from foo import do_something
do_something(x)
and suppose do_something will log an error if x was unacceptable input. Is there some quick hack that would cause an exception to be raised if do_something logs an error? Or is the only way to edit foo's source?
It's not clear if you want to still log the error, but you can try something like:
if error_is_true:
raise Exception("error message...")
With log:
try:
my_function()
except Exception:
logger.exception("error msg...")

How to throw more than 1 possible exception for a single statement in python

I have this statement:
try:
cx_oracle..connect(username/password#hostname:port/service)
except cx_Oracle.DatabaseError:
#do_stuff
Let's say I provide a valid username, an empty password, an invalid hostname and an invalid service name; and I am writing conditions inside except block so that based on Oracle error code something will be done.
How can I list out all possible database errors without correcting the first error that has occurred?
Actual o/p: TNS: listener does not currently know of service requested
Required o/p: TNS: listener does not currently know of service requested
empty password
Invalid host
You can put multiple errors in a tuple. Then you can access whichever error with e.
try:
cx_oracle..connect(username/password#hostname:port/service)
except (cx_Oracle.DatabaseError, Error1, Error2) as e:
# do stuff
You can also have multiple excepts.
try:
cx_oracle..connect(username/password#hostname:port/service)
except cx_Oracle.DatabaseError:
# do stuff
except Error1:
# do stuff
I had a similar problem not too long ago, found this somewhere on stackoverflow, it catches multiple errors:
try:
cur.execute("insert into project_source_code(project, path) values(:project_id,:prj_path)",(project_id, prj_path))
except cx_Oracle.DatabaseError as e:
error, = e.args
print(error.code)
print(error.message)
print(error.context)

Python handle custom exception from java web service

I have a java web service and python client using suds. My server raises custom exceptions which I would like to handle in the python script. Is it possible to catch them or it always will be caught as suds.WebFault exception?
suds.WebFault has fault field that has information about fault.
except suds.WebFault, e:
print e.fault.faultstring
print e.document
You can have your program to analyze server custom exception from WebFault and create new exception class(es) for every specific server exception then catch suds.WebFault exception, read server exception details and raise your custom exception.
class MyException(suds.WebFault):
pass
def convertServerException(e):
if e.fault.faultstring == 'exception1':
return MyException()
#...add more exception handling cases here
#...
try:
#...make a WebService call
except suds.WebFault, e:
print e
print e.fault
raise convertServerException(e)

Are all HttpError in python subclasses of IOError

In our code we catch IOError and log it before reraising. I am getting a "connection reset by peer", but nothing in the logs. Is "connection reset by peer" a subclass of IOError in python?
.....
File "/usr/lib/python2.5/httplib.py", line 1047, in readline
s = self._read()
File "/usr/lib/python2.5/httplib.py", line 1003, in _read
buf = self._ssl.read(self._bufsize)
error: (104, 'Connection reset by peer')
The stack trace you pasted looks like some Exception of class error with arguments (104, 'Connection reset by peer).
So it looks like it's not a HTTPError exception at all. It looks to me like it's actually a socket.error. This class is indeed a subclass of IOError since Python 2.6.
But I guess that's not your question, since you are asking about HttpError exceptions. Can you rephrase your question to clarify your assumptions and expectations?
Comment from usawaretech:
How are you finding out it is a socket
error? MY code is something like:
try:risky_code(); except IOError:
logger.debug('...'); raise; As I am
assuming that HttpError is a subclass
of IOError, when I get that exception,
I am assuming that it be logged. There
is nothing in my logs
I guess it is a socket.error because I used the index of the standard library documentation, and because I encountered this error before.
What version of Python are you using? I guess it's Python 2.5 or earlier.
If your intent is to log and re-raise exceptions, it would be a better idea to use a bare except:
try:
risky_code()
except:
logger.debug(...)
raise
Also, you can find the module where the exception class was defined using exception.__module__.

Categories

Resources