473,657 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Catching very specific exceptions

I am running the following code:

import socket

host = '9.9.45.103'
port = 10001

conn = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
conn.connect((h ost, port))

When conn.connect() is run, there can be two different exceptions:

socket.error: (10061, 'Connection refused')
socket.error: (10060, 'Operation timed out')

How can I set up exceptions for each of these differently? Normally I
would use:

except socket.error:
code goes here...

Of course, though, these are two separate error messages under the same
error handler though. I've tried:

except socket.error, (10061, 'Connection refused'):
and
except (socket.error, 10061, 'Connection refused'):

to no avail. What do I need to do to catch each one specifically?

Thanks,

Harlin Seritt

Jan 22 '06 #1
6 5976
Harlin Seritt <ha**********@y ahoo.com> wrote:
except socket.error:
code goes here...

Of course, though, these are two separate error messages under the same
error handler though. I've tried:

except socket.error, (10061, 'Connection refused'):
and
except (socket.error, 10061, 'Connection refused'):

to no avail. What do I need to do to catch each one specifically?


what I've done in such situations is

except socket.error, e:
if e.errno == 10061:
...
elif e.errno == 10060:
...
else:
raise

Not sure the code in a socket.error has attributename 'errno', but I
hope you get the general idea.
Alex
Jan 22 '06 #2
Alex Martelli wrote:
what I've done in such situations is

except socket.error, e:
if e.errno == 10061:
...
elif e.errno == 10060:
...
else:
raise

Not sure the code in a socket.error has attributename 'errno', but I
hope you get the general idea.


If it does not, or as a more generally applicable solution (though less
readable), one can use the args attribute:

except socket.error, e:
if e.args[0] == 10061:
...
elif e.args[0] == 10060:
...

args is just the tuple formed from the positional arguments passed to
the __init__() of the exception object when it is created, as if you did:

class Exception:
def __init__(self, *args):
self.args = args
-Peter

Jan 22 '06 #3
In article <1h************ **************@ mail.comcast.ne t>,
al***@mail.comc ast.net (Alex Martelli) wrote:
Harlin Seritt <ha**********@y ahoo.com> wrote:
except socket.error:
code goes here...

Of course, though, these are two separate error messages under the same
error handler though. I've tried:

except socket.error, (10061, 'Connection refused'):
and
except (socket.error, 10061, 'Connection refused'):

to no avail. What do I need to do to catch each one specifically?


what I've done in such situations is

except socket.error, e:
if e.errno == 10061:
...
elif e.errno == 10060:
...
else:
raise


This is not portable, however. I'm guessing you're running on Windows,
because the 10061 corresponds to:

{WSAECONNREFUSE D, "Connection refused"},

in Python-2.3.4/Modules/socketmodule.c: set_error(). See
http://tinyurl.com/gth2 for more winsock error codes.

It would be nice if the socket library threw more specific exceptions, but
given that the underlying operating systems export such a wide variety of
system-level errors, it's not clear it's feasible, even if one wanted to
put the effort into it. Which brings us back to having to resort to
unportable tricks like the above to decipher the inner meaning.

But, the real question is, WHY do you want to differentiate between these?
The only reason to want to know which kind of connection failure you got is
because you want to do something different on some errors. What are you
going to do differently when you get one of these?

socket.error: (10061, 'Connection refused')
socket.error: (10060, 'Operation timed out')

Operationally, they're pretty much the same. One might guess that on a
timeout, it's worth waiting a while and trying again, but it may be worth
doing that on a refusal as well. Perhaps you caught the remote system
right after a reboot when the kernel network code is up, but the particular
service you're trying to connect to hasn't started yet? Perhaps there's
some kind of load-limiting in use? Perhaps the remote system is validating
connections by reverse DNS checks, and inconsistent DNS caches are causing
some connections to fail while others succeed? Any of these might deserve
a retry.
Jan 22 '06 #4
Thanks for the effort on this last post, Roy. You asked what I was
hoping to do differently on these two very minutely different error
messages. What I have been trying to do for some time is to write a
ping client (for Win32 platform -- Yes, I develop almost exclusively
for Win32 environment, unfortunately) that would be a bit less buggy
than ones already written, avoid Twisted, and not even involve myself
in pynms (way overkill for what I want and need).

I am finding that with the many quirks (and really bad foundation for
Win32 APIs) that I am having to write a lot of voodoo code so to speak.
If I use a dummy port... let's say port 10001 for example... I can
attempt to connect to a machine at this port. If I get an error that
says "Connection refused", I know that the node is up but is just not
going to allow a connection. On the other hand, if I try to connect to
a node and it's really not up, I'll get a "Connection timed out" error.
In this manner I can really tell if a node is up or not (providing a
TCP/IP stack is installed there). This really what I've wanted. I am
not so concerned whether or not the node pongs back in a certain amount
of time.

Yeah normally it's annoying when people ask what you're trying to do
when you ask a specific question, but in this case it's probably
necessary to explain myself before some are willing to help out. I'm
really not interested in even negotiating a successful connection on a
specific port, but this is just a way to tell if something is up or
down (and perhaps the only real way to do it running from a Win32
platform). Thanks for the help. However, if you do have suggestions on
how to get this done better, I am more than glad to hear it!

Thanks,

Harlin Seritt

Jan 22 '06 #5
"Harlin Seritt" <ha**********@y ahoo.com> wrote:
I am finding that with the many quirks (and really bad foundation for
Win32 APIs) that I am having to write a lot of voodoo code so to speak.
Yeah, tell me about it. My current project at work is porting our IPv6
management package (including ICMP ping) to windows; "many quirks" would be
a good way to describe it!
If I use a dummy port... let's say port 10001 for example... I can
attempt to connect to a machine at this port. If I get an error that
says "Connection refused", I know that the node is up but is just not
going to allow a connection.


Maybe. It could be that some firewall between you and the target is
blocking things. Depending on how the firewall is programmed, this may
show up as a timeout or as a connection refused (although the former would
be more common).

It's also not always a clear-cut question what "up" means. Some operating
systems can get into modes where for all intents and purposes they've
crashed, but they're still answering pings and/or actively refusing
connections.

The traditional way to tell if a node is up is to send it an ICMP echo
request, rather than trying to connect to a TCP port. You might want to
look into using that instead of trying to connect to random ports. Not
that that ICMP doesn't have its own problems :-)
Jan 22 '06 #6
Reasons why it still won't work:

* Firewall
* Unknown-modes-operating-systems-get-into

Yeah, I dont think these things can be avoided. Nonetheless, if I can
come up with some way (via help from this group--thank God!) to find if
the node is up (barring the two aforementioned reasons), I am doing
well. Maybe my standards are not so high. :-|

Nonetheless, thanks for the help and the commentary. I was beginning to
think I was losing my mind.

Harlin

Jan 22 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1768
by: Keith Bolton | last post by:
I am handling exceptions currently using try, except. Generally I don't handle specific exceptions and am catching all. Then if an exception occurs, I would like to capture that error string. However, in the documentation it seems like there is not a way to get the extra str data if you are handling all exceptions and not specifically. Is there? thanks -keith
2
1845
by: Shravan | last post by:
Hi, Does anybody know how to catch unhandled exceptions in an application. I have tried using AppDomain.UnhandledException Event Application.ThreadException Event but they were not catching unhandled exceptions always. There are not working in some cases.
7
2332
by: cmay | last post by:
FxCop complains every time I catch System.Exception. I don't see the value in trying to catch every possible exception type (or even figuring out what exceptions can be caught) by a given block of code, when System.Exception seems to get the job done for me. My application is an ASP.Net intranet site. When I catch an exception, I log the stack trace and deal with it, normally by displaying an error
12
6102
by: Vasco Lohrenscheit | last post by:
Hi, I have a Problem with unmanaged exception. In the debug build it works fine to catch unmanaged c++ exceptions from other dlls with //managed code: try { //the form loads unmanaged dlls out of which unmanaged exception //get thrown
2
1302
by: Eric Sabine | last post by:
I built a generic exception handler form which allows the user to get information from it, print it, email it, etc. for exceptions for which I explicitly didn't handle in code, such as missing permissions on a stored procedure, etc. I use this exception handler in all of my applications and it can be called as simply as follows try ... catch ex as sqlexception ExceptionHandler(ex, otherData1, otherData2)
5
2226
by: Simon Tamman | last post by:
I have an object named DisasterRecovery. The Ctor of this object is this: private DisasterRecovery() { Application.ThreadException+= new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); }
5
3560
by: Paul Sijben | last post by:
All, in a worker thread setup that communicates via queues is it possible to catch exceptions raised by the worker executed, put them in an object and send them over the queue to another thread where the exception is raised in that scope? considering that an exception is an object I feel it ought to be possible, however I do not see how to go about it.
24
4928
by: usenet | last post by:
I am unable to catch floating exceptions (e.g. divide by 0 or 0/0) using the standard exceptions defined in stdexcept. What is the recommended way to catch such exceptions? Thanks, Song
12
18295
by: Karlo Lozovina | last post by:
I'm not sure if Python can do this, and I can't find it on the web. So, here it goes: try: some_function() except SomeException: some_function2() some_function3() ...
3
3278
by: john | last post by:
I wrapped some fortran code using F2PY and need to be able to catch fortran runtime errors to run the following: # "grid" is a wrapped fortran module # no runtime errors incurred when run with the correct inputs for filetype #------------------------------- def readGrid( self, coord='xyz' ): mg = ( '.FALSE.', '.TRUE.' ) form = ( 'FORMATTED', 'UNFORMATTED' )
0
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8617
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7352
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2742
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.