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'
If you are familiar with Java you can do thing the same way in Python - with a
try: ... except: statement.
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 except
statement or use an except statement with no error specified which
will handle all errors.
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
except statements are used.
With a try ... except statement you can also use an else
clause which is executed only if no exception was generated. This is not the same
as moving the code from the else to the try
section as an exception triggered in the else section will
not be handled.