User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 391,703 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,196 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser:
Views: 1428 | Replies: 6
Reply
Join Date: Jun 2006
Location: America
Posts: 186
Reputation: Matt Tacular is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 2
Matt Tacular's Avatar
Matt Tacular Matt Tacular is offline Offline
Junior Poster

Error/Exception handling help

  #1  
Dec 31st, 2006
I have searched google, but found nothing, I'm not even sure if this is what you call it. But in my program I am writing, if someone hits enter by mistake without entering anything, it errors, is there a way to avoid that?

Another error that happens is if the program is expecting a number and gets a letter.
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Dec 2006
Posts: 384
Reputation: woooee is on a distinguished road 
Rep Power: 2
Solved Threads: 52
woooee woooee is offline Offline
Posting Whiz

Re: Error/Exception handling help

  #2  
Dec 31st, 2006
Another error that happens is if the program is expecting a number and gets a letter.
if input_string.isdigit():
   do_something()
else :
   print "Enter a number"
if someone hits enter by mistake without entering anything, it errors, is there a way to avoid that?
if (input_string) and len(input_string) > 0 :
## -----or
try :
   input_str = raw_input( "Enter a Number --> " )
except :
   print "No number entered"
## -----or the old stand by
input_str = ""
while (len(input_str) < 1 )  or (not input_str.isdigit() ):
   input_str = raw_input( "Enter a Number --> " )
Reply With Quote  
Join Date: Jun 2006
Location: America
Posts: 186
Reputation: Matt Tacular is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 2
Matt Tacular's Avatar
Matt Tacular Matt Tacular is offline Offline
Junior Poster

Re: Error/Exception handling help

  #3  
Dec 31st, 2006
could someone be kind enough to elaborate on that? I'm sorry but to tell you the truth I just don't understand what any of that does... I get the whole try and except part, but thats it.
Reply With Quote  
Join Date: Jul 2006
Posts: 562
Reputation: jrcagle is on a distinguished road 
Rep Power: 4
Solved Threads: 72
jrcagle jrcagle is offline Offline
Posting Pro

Re: Error/Exception handling help

  #4  
Dec 31st, 2006
Well, in general, you should validate your input. What that means is making mathematically sure that the user enters a correct something, or else the program prints an error and continues on with life. That's what the first code snippet above does: if the user didn't type a (non-negative!) integer, he gets an error.

A more general way of validating the input is to let Python do it for you! If you try to convert a non-integer to an integer, you get a ValueError exception thrown. The second snippet of code above shows how to catch the exception and avoid having your program break.

Jeff
Reply With Quote  
Join Date: Jun 2006
Location: America
Posts: 186
Reputation: Matt Tacular is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 2
Matt Tacular's Avatar
Matt Tacular Matt Tacular is offline Offline
Junior Poster

Re: Error/Exception handling help

  #5  
Jan 1st, 2007
Are their any good tutorials for this kind of stuff?
Reply With Quote  
Join Date: Jul 2006
Posts: 562
Reputation: jrcagle is on a distinguished road 
Rep Power: 4
Solved Threads: 72
jrcagle jrcagle is offline Offline
Posting Pro

Re: Error/Exception handling help

  #6  
Jan 1st, 2007
Here's my stab at a quick tutorial:

Validating Input

Any time your program receives input from a device, it needs to check whether the input is valid. By far, the two most common points for input are

(1) When the user types something at the keyboard, and
(2) When data is read from a file.

If your program fails to check the input for validity, then your program runs the risk of crashing, which can lead to the user being frustrated at his hard work going down the tubes and can even become an entry point for hackers (not so much in Python I think, but very true in C).

Here's an example:

  1. (after two hours of game play ... )
  2. What is your name? King Arthur of Camelot
  3. What is your quest? To seek the Holy Grail
  4. What is your favorite number? Three
  5.  
  6. Traceback (most recent call last):
  7. File "<pyshell#0>", line 1, in -toplevel-
  8. a = int(raw_input("What is your favorite number? "))
  9. ValueError: invalid literal for int(): Three
  10.  
  11. >>> @$#@$#$#%^%


How do you validate input?

First, Decide what the input should be. There are two things to consider: type and range. If your program is expecting a certain data type -- say, an integer -- then nothing else should be allowed. If the integer must be non-negative, then negatives should be verboten.

Second, at the point of input, verify that the input has the right type and range. This can happen either by using a try-except clause, or by manual checking, or both together

  1. try:
  2. number = int(raw_input("Enter an integer between 0 and 8: "))
  3. except:
  4. print "Invalid input!"
  5. number = 0
  6. if not 0 <= number <= 8:
  7. print "Your number is out of range!"
  8. number = 0

Two things are important features in the code above. First, the user is always given feedback if his input is invalid. This frees him from the tyranny of the blank screen. Second, when the input is invalid, the value of number is set to a default. The default value should be one that is compatible with the rest of your code.

Alternatively, if no default value is suitable, you can enclose your validation in a while loop:

  1. while True:
  2. try:
  3. number = int(raw_input("Enter an integer between 0 and 8: "))
  4. except:
  5. print "Invalid input!"
  6. if not 0 <= number <= 8:
  7. print "Your number is out of range!"
  8. else:
  9. break

Here, if the number is an integer and in range, the break statement will get the user out of the loop. Else, he will be forced to try again.

To sum up: always check input from keyboard and disk to make sure it is valid. Use try-except and conditionals to perform the checks, and use default values and while loops to recover from input errors. And always, always give the user feedback when an error occurs.

Hope it helps,
Jeff
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 965
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 5
Solved Threads: 42
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Posting Shark

Re: Error/Exception handling help

  #7  
Jan 1st, 2007
Pack it into a function then you can use it again and again:
[php]def get_integer():
'''loops until integer value is entered, then returns it'''
while True:
try:
num = int(raw_input("Enter integer number: "))
return num
except ValueError:
print "Please, enter integer number!"

# get integer value from the user
val = get_integer()
print val
[/php]
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb Python Marketplace
Thread Tools Display Modes

Similar Threads
Other Threads in the Python Forum

All times are GMT -4. The time now is 2:44 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC