How to handle errors?

Steve D'Aprano steve+python at pearwood.info
Thu Oct 20 18:16:37 EDT 2016


On Fri, 21 Oct 2016 06:48 am, SS wrote:

> The following script works fine:
> 
> #!/bin/python
> 
> import socket
> 
> str = raw_input("Enter a domain name: ");
> print "Your domain is ", str
> print socket.gethostbyname(str)
> 
> You provide it a hostname, it provides an IP.  That works fine.  But I
> need a way to handle errors.  For example:
[...]
> I would like to be able to handle that error a bit better.  Any ideas?

How do you want to handle the error? You can't just say "handle errors" --
you have to actually decide what do you want to do. If the user provides an
invalid hostname, what do you want to happen? If the network is down, what
do you want to happen?

Sometimes the best way to handle errors is not to handle them at all. If you
don't know what to do with a particular error condition, *don't* handle it.
Let it just go through to the user.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list