NameErroris raised and also the location where the error was detected is printed. This is what an error handler for this error does.
Enterkey. When your computer prompts you for input, instead press
[ctrl-d]on a Mac or
[ctrl-z]with Windows and see what happens. (If you're using Windows and neither option works, you can try
[ctrl-c]in the Command Prompt to generate a KeyboardInterrupt error instead).
EOFErrorwhich basically means it found an end of file symbol (which is represented by
ctrl-d) when it did not expect to see it.
try..exceptstatement. We basically put our usual statements within the try-block and put all our error handlers in the except-block.
tryblock and then put handlers for the appropriate errors/exceptions in the
exceptclause can handle a single specified error or exception, or a parenthesized list of errors/exceptions. If no names of errors or exceptions are supplied, it will handle all errors and exceptions.
exceptclause associated with every
tryclause. Otherwise, what's the point of having a try block?
elseclause associated with a
elseclause is executed if no exception occurs.
raisestatement by providing the name of the error/exception and the exception object that is to be thrown.
ShortInputException. It has two fields -
lengthwhich is the length of the given input, and
atleastwhich is the minimum length that the program was expecting.
exceptclause, we mention the class of error which will be stored
asthe variable name to hold the corresponding error/exception object. This is analogous to parameters and arguments in a function call. Within this particular
exceptclause, we use the
atleastfields of the exception object to print an appropriate message to the user.
time.sleepfunction so that the program runs slowly (Python is very fast by nature). When the program is still running, press
ctrl + cto interrupt/cancel the program.
KeyboardInterruptexception is thrown and the program quits. However, before the program exits, the finally clause is executed and the file object is always closed.
Noneor a variable which is an empty sequence or collection is considered
Falseby Python. This is why we can use
if: fin the code above.
tryblock and subsequently releasing the resource in the
finallyblock is a common pattern. Hence, there is also a
withstatement that enables this to be done in a clean manner:
openfunction with the
withstatement - we leave the closing of the file to be done automatically by
withstatement. It fetches the object returned by the
openstatement, let's call it "thefile" in this case.
thefile.__enter__function before starting the block of code under it and always calls
thefile.__exit__after finishing the block of code.
finallyblock should be taken care of automatically by the
__exit__method. This is what helps us to avoid having to use explicit
try..finallystatements. We have seen how to create our own exception types and how to raise exceptions as well.