[Tutor] reading stdin?

Doug Stanfield DOUGS@oceanic.com
Sat, 17 Feb 2001 07:43:27 -1000


[D-Man wrote:]
> On Sat, Feb 17, 2001 at 05:20:07PM +0100, J=F6rg W=F6lke wrote:
> [snip]
> | > >>> try :
> | > ...     data =3D int( raw_input( "Enter a number: " ) )
> | > ... except ValueError , err :
> | > ...     print "You didn't enter a valid number"
> | > ...
> |=20
> | excuse me if that's a silly question:
> | why not just
>=20
> It's a perfectly good question.
>=20
> | try:
> |      data =3D input("Enter number: ")
> | except:
> |      "wrong"
> |=20
> | which would trap all errors?
>=20
> This is exactly why you don't want to use a universal except clause =
--
> do you really want to catch KeyBoardError, OutOfMemoryError,
> SystemExit and ComputerExplodingError?  Using a universal except will
> work if you never get one of these kind of errors, but if you do get
> one, the program won't behave as expected.  It is generally good to =
be
> as explicit as you can in what exceptions you want to catch and
> handle.  I didn't do it here, but in an earlier post (see archives) I
> used the exception to tell the user what exactly they entered that
> wasn't a valid number.  By explicitly catching certain exceptions, =
you
> can use their data to improve the error handling.

In addition, please note the difference between 'raw_input' and =
'input'.
The use of 'input' is generally unsafe.  Using 'raw_input' is almost =
always
what you want in this scenario of getting data from a user.

-Doug-