>A Byte of Python

Try..Except

To show the usage of exceptions, we will try to read input from the user and see what happens.

>>> s = raw_input('Enter something --> ')
Enter something --> Traceback (most recent call last):
  File "<stdin>", line 1, in ?
EOFError
>>>
      

Here, we ask the user (which is you in this case) for input and if you press Ctrl-d i.e. the EOF (end of file) character, then Python raises an error called EOFError. Next, we will see how to handle such errors.

We can handle exceptions using the try..except statement. We basically put our usual statements within the try-block and we put all the error handlers in the except-block.