Where do add an exception block
Posted by enquirer (enquirer), 24 January 2004I've written a piece of code that prompts for input from the user, and I need to catch any non-numeric input he makes. I can do by reading a test string and testing it with a Regular Expression, but shouldn't I be using an exception? If so, do I just put all my code into a try block?
Posted by admin (Graham Ellis), 24 January 2004Yes, you should be using an exception; it's Python's way of letting you trap errors in the environment in which your program is running (e.g. user input, file system, network failures) and also the ideal way of trapping functions that don't want to return a result but rather a warning / error. For example, if you have a playing card object and want to return the suit, have the method raise an exception when asked about the suit of the joker.
Moving on to the second part of the code - no, don't just put a try around all your code. A try / except pair is a conditional statement in a similar way to an if / else, and it's just as important to get the block ends right. If you're making a number of inputs, you will have design decisions to make as to whether to
a) Put a series of try / except blocks sequentially after one another in the code (do this if you want to go on to each subsequent input even if the previous one has trapped)
b) Put all your inputs in a single try block (rarely recommended, but you could do this if you simpy want to error out if any of the inputs is in error)
c) Nest your try blocks (do this is you want to avoid any further input from your user once you hit a data error, but want to default values instead).
Here's an example of option (c):
If you enter nothing at all (just press enter to the first prompt), both inputs are defaulted.
If you enter one value, and just press enter for the second, the second value is defaulted to 100 greater than the first.
If you enter two values, they are assigned to val1 and val2.
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: firstname.lastname@example.org • WEB: http://www.wellho.net • SKYPE: wellho