Errors and Exceptions
If you (and you will) write code that doesn’t work, you will get an error message.
What are exceptions?
Exceptions is what you get after you have first ran the program.
There are different kind of errors in Python, here are a few of them:
ValueError, TypeError, NameError, IOError, EOError, SyntaxError
This output show a NameError:
>>> print 10 * ten Traceback (most recent call last): File "", line 1, in NameError: name 'ten' is not defined and this output show it's a TypeError >>> print 1 + 'ten' Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str'
- Exception Handling in Python
- Exception Handling in Python: Writing a Robust Python Program
- Python Programming – Exception Handling
Try and Except
There is a way in Python that helps you to solve this: try and except
#Put the code that may be wrong in a try block, like this: try: fh = open("non_existing_file") #Put the code that should run if the code inside the try block fails, like this: except IOError: print "The file does not exist, exiting gracefully" #Putting it together, it will look like this: try: fh = open("non_existing_file") except IOError: print "The file does not exist, exiting gracefully" print "This line will always print"
import sys try: name = raw_input("what is your name?") except EOFError: print " You did an EOF... " sys.exit() If you do an ctrl+d, you will get an output like this: >>what is your name? >>You did an EOF...
try: name = raw_input("Enter your name: ") print "You entered: " + name except KeyboardInterrupt: print "You hit control-c" If you press ctrl+c, you will get an output like this: >>Enter your name: ^C >>You hit control-c
while True: try: x = int(raw_input("Please enter a number: ")) break except ValueError: print "Oops! That was no valid number. Try again..."
For a full list of all Python’s built-in exceptions, please see this post