26.14. Python Errors and Exception Handling

Python signals errors by throwing exceptions. Unless redirected, all error messages are written to the standard error stream; normal output from the executed commands is written to standard output. Some types of errors are unconditionally fatal and cause the Python program to exit with a nonzero exit status; these errors typically are due to internal system inconsistencies or are sometimes the result of running out of memory. Python error handling includes two phases: exception detection and exception handling. Python developers are allowed a great deal of control in error handling. To add error detection, simply wrap the code in a try-except statement. The code that follows the except statement will execute upon exception. Anticipating which errors your code might encounter is important because any exception not handled directly in your code will be fatal. You can find a hierarchy of standard exceptions at http://docs.python.org/lib/module-exceptions.html.

In the following code, Python attempts to execute the statements between the try and the first except statement. If an error is encountered, execution of the try statements stops and the error is checked against the except statements. Execution progresses through each except statement until it finds one that matches the generated exception. If a matching except statement is found, the code block for that exception is executed. If there is no matching except statement in the try block, ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.