Python Tutorial, Release 3.9.5 The rest of the line provides detail based on the type of exception and what caused it. The preceding part of the error message shows the context where the exception occurred, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input. bltin-exceptions lists the built-in exceptions and their meanings. It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using$_{Control-C}$ or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception. The$_{try}$ statement works as follows. A$_{try}$ statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same$_{try}$ statement. An except clause may name multiple exceptions as a parenthesized tuple, for example: A class in an$_{except}$clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order: (continues on next page) Chapter 8. Errors and Exceptions 58 classB (Exception): pass classC (B): pass classD (C): pass for cls in [B, C, D]: try : raise cls() ... except (RuntimeError,TypeError,NameError): ... pass >>> while True : ... try : ... x =int(input("Please enter a number:")) ... break ... except ValueError: ... print("Oops! That was no valid number. Try again... ") ... • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer $_{try}$statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above. • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the$_{except}$keyword, the except clause is executed, and then execution continues after the$_{try}$ statement. • If no exception occurs, the except clause is skipped and execution of the$_{try}$ statement is finished. • First, the try clause (the statement(s) between the$_{try}$ and$_{except}$keywords) is executed. 8.3 Handling Exceptions