I'm trying to catch the exception when connecting to database and have no connection, but I always freeze at pyodbc.connect(connstr). I tried all errors from documentation, tried just "except Exception" but I see my program just freeze when cannot connect to database and don't check except section. (Freeze is caused by my on-purpose disconnection from database and program just does nothing (windows "no answer") until my hard reset):
import pyodbc
connstr=('DRIVER={SQL Server Native Client 11.0};Server="server_ip";port=1433;Network Library=DBMSSOCN;Database="name";uid="uid";pwd="pwd";')
try:
print("I'm here - no problem")
conn=pyodbc.connect(connstr)
print("of course not here")
except ...no_matter_what_I_write_here... :
print("but never there too")
It was too simple (thank You Pynchia for Your suggestion):
try:
conn=pyodbc.connect(connstr, timeout=5)
except pyodbc.Error as err:
print("Couldn't connect")
Assuming you are not connecting on thread. Coz Signals will not work in non main thread.
import signal
from contextlib import contextmanager
class TimeoutError(Exception): pass
#contextmanager
def time_limit(seconds):
def signal_handler(signum, frame):
raise TimeoutError("Time out")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
try:
with time_limit(10):
conn=pyodbc.connect(connstr)
except TimeoutError as e:
print "couldn't connect for long time"
Related
I want to create a connection timeout exception using urlopen.
try:
urllib2.urlopen("http://example.com", timeout = 5)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
This is the code
I want to create a timeout that this code would bring an exception.
Thank You in advance.
You need to catch socket.timeout exception, check example below.
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except socket.timeout, e:
# For Python 2.7
raise MyException("There was an error: %r" % e)
I strongly recommend using Requests library for making requests, it will make your life easier.
The following function allows to use the with-statment and the a pop connection. But if the connection is not established, the quit() in finally will raise an exception. How can this be fixed?
#contextmanager
def pop_connect(server, user, password, timeout, use_SSL=False):
try:
pop = poplib.POP3_SSL if use_SSL else poplib.POP3
pop_conn = pop(server, timeout=timeout)
pop_conn.pass_(password)
yield pop_conn
except poplib.error_proto as pop_error:
print('Authentication for receiving emails failed:{}'.format(pop_error))
except OSError as os_error:
print('Name resolution or connection failed:{}'.format(os_error))
finally:
pop_conn.quit()
I suppose you can put your pop_conn.quit() in a try: with pass as corresponding except action:
finally:
try:
pop_conn.quit()
except <WhaterverException>:
pass
The solution is to rethrow the exceptions in the handlers. The contextmanager than does not except the yield:
#contextmanager
def pop_connect(server, user, password, timeout, use_SSL=False):
try:
pop_conn = poplib.POP3_SSL(server,timeout=timeout) if use_SSL else poplib.POP3_SSL(server,timeout=timeout)
pop_conn.user(user)
pop_conn.pass_(password)
yield pop_conn
except poplib.error_proto as pop_error:
print('Receiving mail failed:{}'.format(pop_error))
raise
except OSError as os_error:
print('Name resolution or connection failed:{}'.format(os_error))
raise
finally:
try:
pop_conn.quit()
except UnboundLocalError:
pass
Every now and then setting up a tunnel using sshtunnel.py fails because the gateway (ssh_host) complains the first time I connect to it. I would like to give it a few retries before giving up:
for attempt in range(5):
try:
forwarder.start()
except Exception, e:
print 'Error (trying again in five seconds):\n' + format(e.message))
time.sleep(5)
else:
break
else:
print 'Failed to setup a connection to the gateway'
sys.exit(1)
However, the error is not 'detected'. I took a peek in the sshtunnel.py code and found that the following code catches the related Paramiko exception:
except paramiko.ssh_exception.AuthenticationException:
self.logger.error('Could not open connection to gateway')
return
How do I catch this in my try:?
An SSHTunnel.py project member advised me to add forwarder._check_is_started() to my code:
for attempt in range(5):
try:
forwarder.start()
forwarder._check_is_started()
except BaseSSHTunnelForwarderError as e:
print 'Error (trying again in five seconds):\n' + format(e.message))
time.sleep(5)
else:
break
else:
print 'Failed to setup a connection to the gateway'
sys.exit(1)
I have a function that returns the DB connection handler from MongoDB. I have various other functions that makes a call to the DB, I figure let's throw the connection handler into a function so I don't have to define it in every function.
Does this look right? I guess my question is, if it can't make a connection to the DB server, it will print both messages Could not connect to server and No hosts found How can I go about only printing "Could not connect to the server."
def mongodb_conn():
try:
conn = pymongo.MongoClient()
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to server: %s" % e
return conn
def get_hosts()
try:
conn = mongodb_conn()
mongodb = conn.dbname.collection
b = []
hosts_obj = mongodb.find({'_id': 'PR'})
for x in hosts_obj:
print x
except:
print "No hosts found"
get_hosts()
Move your conn = mongodb_conn() call out of the try .. except handler, and test if None was returned:
def get_hosts()
conn = mongodb_conn()
if conn is None:
# no connection, exit early
return
try:
mongodb = conn.dbname.collection
b = []
hosts_obj = mongodb.find({'_id': 'PR'})
for x in hosts_obj:
print x
except:
print "No hosts found"
You should, at all cost, avoid using a blanket except however; you are catching everything now, including memory errors and keyboard interrupts, see Why is "except: pass" a bad programming practice?
Use specific exceptions only; you can use one except statement to catch multiple exception types:
except (AttributeError, pymongo.errors.OperationFailure):
or you can use multiple except statements handle different exceptions in different ways.
Limit the exception handler to just those parts of the code where the exception can be thrown. The for x in hosts_obj: loop for example is probably not going to throw an AttributeError exception, so it should probably not be part of the try block.
Note that you'll need to adjust your mongodb_conn() function to not try and use the conn local if it has never been set; you'll get an UnboundLocal error if you do:
def mongodb_conn():
try:
return pymongo.MongoClient()
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to server: %s" % e
Now the function returns the connection if successful, None if the connection failed.
You can also check if the server is available
like this:
from pymongo.errors import ConnectionFailure
client = MongoClient()
try:
# The ismaster command is cheap and does not require auth.
client.admin.command('ismaster')
except ConnectionFailure:
print("Server not available")
I want to create socket errors (By doing things, obviously) but I've no idea how I should test if my script handles errors properly (If it dectes them.)
Currently, my code is this:
except socket.error as err:
print "Connection lost, waiting..."
time.sleep(5)
In theory, it should handle all the socket errors, print and then sleep (It's a part of a while loop.).
Any idea of how can I test it to see how it handles errors?
Use the raise statement:
try:
raise socket.error
except socket.error as err:
print "Connection lost, waiting..."
time.sleep(5)
Yet another example:
try:
raise AttributeError
except AttributeError:
print 'Sorry'
#Sorry
Also take a look at here and here