Page 231 - Beginning Programming with Pyth - John Paul Mueller
P. 231

try:
raise ValueError print("Raising an exception.")
except ValueError: print("ValueError Exception!") sys.exit()
finally:
print("Taking care of last minute details.")
print("This code will never execute.")
In this example, the code raises a ValueError exception. The except clause executes as normal when this happens. The call to sys.exit() means that the application exits after the exception is handled. Perhaps the application can’t recover in this particular instance, but the application normally ends, which is why the final print() function call won’t ever execute.
The finally clause code always executes. It doesn’t matter whether the exception happens or not. The code you place in this block needs to be common code that you always want to execute. For example, when working with a file, you place the code to close the file into this block to ensure that the data isn’t damaged by remaining in memory rather than going to disk.
2. Click Run Cell.
The application displays the except clause message and the finally clause message, as shown in Figure 10-15. The sys.exit() call prevents any other code from executing.
Note that this isn’t a normal exit, so Notepad displays additional information for you. When you use some other IDEs, such as IDLE, the application simply exits without displaying any additional information.
3. Comment out the raise ValueErrorcall by preceding it with two pound signs, like this:
##raise ValueError
Removing the exception will demonstrate how the finally clause actually works.
   




















































































   229   230   231   232   233