Home > Python >
Handling Errors in Python | Sitemap Search |
|
Sections Membership Features
Recent comments
very difficult by alfin Taking the credit for another persons work ? by curious dude. |
Handling Errors in PythonPosted by martin on 25 Aug 2002. Avoid the ugly error messages in Python by implementing custom error handlers. When you're writing an application you cannot test all input to the program that users may supply. The default behavior when an error condition occurs in Python is to print an ugly error message and halt processing of the script. Example: print 1/'a' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unsupported operand type(s) for /: 'int' and 'str' How do I handle the errorsIf you are familiar with Java you can do thing the same way in Python - with a
Example: try: print 1/'a' except TypeError: print 'Division is unsupported on this type of data' With this little modification your program will run and you can print a nicer
error message. This statement will handle only TypeError
errors, if you want to handle other errors you can add another Example:
def get_line(prompt) :
"""Reads a line of user input."""
try :
while 1 :
line = raw_input(prompt + ': ')
if line :
return line
except EOFError :
return ''
except KeyboardInterrupt :
print 'Cancelled by user'
return ''
name = get_line('Enter your name')
print name
This is a simple script to request user input, note how the two
With a |