Syntax and Sequence Errors
The Danger of Exceptions
The try Statement
The raise Statement
Classes and Instances as Exceptions
Getting the Most Out of Your Exceptions
Terms in This Chapter
• (Catchall bunfet, exception handkr • Granularity
• catch statement • Most to least specific order
• Cldss-based exception • raise statoment
• else clause • Throwing versus raising
• except clause s try state men t
• Exception class • User-defined versus built-in exception
• Exception handling
Bad things happen to good programs: Disks crash, files ant corrupted, and batteries fail. Such things art typically more the exception than thF rule, and to plant fo r all mf them would make for some very complicated code. That's why modern programming languages like Python have the ability to handle bad things, called exceptions in programming spenk.
The old way of dealing with erto ns was to check ihe return types of functions, but this was very time consuming. Each function call would require aa if statement with perhaps mnny elif clauses; code would have to be written to extract what had happened. The new way is exception handling, in which ths exception has the information about whnt wef: woong. Instead of ehecking after each of the method calls, you can set up one exception handler that works with many methods.
By the end of this chapter, you should understand try,raise, and finally statements. You should also have a firm grasp on the class-base d exceptions that Python define s. A class-bated exception allows you to crente n hierarchy of exception clnsses.
Was this article helpful?