Python System Study Notes (9) --- Exception Handling

Source: Internet
Author: User

Python has powerful exception handling capabilities and can accurately report error information to users. In Python, exceptions are also objects that can be operated on. All exceptions are members of the base class Exception. All exceptions are inherited from the base class Exception and are defined in the exceptions module. Python automatically stores all the exception names in the built-in namespace, so the program does not need to import the exceptions module to use the exception. Once the system exit exception is thrown and not caught, the program execution ends. If an uncaptured SystemExit exception occurs in an interactive session, the session ends. Try/retry T: capture and recover exceptions in the code, match errors in wait t, and manually commit the code defined in T, and then continue to execute the program (when an exception occurs, after exceptions are caught by the retry t, the program will not be interrupted and the program following the try statement will continue to be executed.) try/finally: whether or not the exception occurs, execute cleanup (when an exception occurs, the program will interrupt the program, but the finally code will be executed) raise: manually submit an exception in the code. Assert: triggers exceptions in program code conditionally. With/as implements the Environment Manager. 1: try statement: the rule of this exception processing syntax is: Execute the statement in try. If an exception is thrown, the execution process jumps to the first limit t statement. If the exception defined in the first primary T matches the exception, the statement in the primary T is executed. If the exception does not match the first occurrence t, the second occurrence T will be searched. There is no limit on the number of tokens allowed to be written. If none of the except T matches, the exception will be passed to the top-level try code that calls this code next. If no exception occurs, run the else block code. A user-defined exception must be written as an instance of the class, rather than a string. Finally can be used in the same try statement as except T and else clauses. 1.1 Use try and try t statements to catch exceptions. try: blockexcept [exception, [data…]: The complete form of blocktry: try/multiple begin t/else statements else is an optional try code block under the first line represents the main action of this statement: the program code to be executed. The limit t clause defines the exception processor thrown in the try code block, while the else clause (if any) provides the processor to be executed when no exception occurs. Import systry: s = raw_input ('test EOFError: ') failed t EOFError: print 'meet eoerror' sys. exit () failed T: print 'hello' 1. 2. Use try and finally. The syntax is as follows: try: blockfinally: block. The execution rule of this statement is: Execute the code in try. · If an exception occurs, execute finally code when the exception is passed to the next try. · If no exception occurs, execute the finally code. The second try syntax is useful when code execution is required no matter whether an exception occurs. For example, if we open a file in python for read/write operations, I will close the file no matter whether an exception occurs during the operation. The two forms conflict with each other. If one is used, the other is not allowed, and the functions are different. try: f = open ('dic. ini ', 'w') f. write ('200') finally: print 'close file' f. close () 1.3 unified try/sort t/finally Clause try: main-action: handle T Exception1: hander1blocks t Exception2: hander2... in the else: else-blockfinally: finally-block statement, the main-action code is executed first. If the program code (main-action) causes an exception, the blocks of blocks will be tested one by one to find statements that match the thrown exception. If Exception1 is thrown, hander1 code block is executed. If Exception2 is thrown, hander2 code block is executed. And so on. If no exception is thrown, The else-block code block is executed. No matter what happens before, when the main-action code block is complete. All finally-blocks are executed. 2. manually raise an exception using the raise statement: custom exception raise [exception [, data] in Python, the simplest form of exception triggering is to enter the keyword raise, the name of the exception to be thrown. Exception names identify specific classes: Python exceptions are the objects of those classes. When a raise statement is executed, Python creates an object for the specified exception class. The raise statement can also specify the initialization parameters for the exception object. Therefore, add a comma and a specified parameter (or a tuple consisting of parameters) after the name of the exception class ). For example, try: raise MyError # throw an Exception yourself. Counter t MyError: print 'a error' [python] class ShortInputException (exception): ''' a user-defined Exception class. '''def _ init _ (self, length, atleast): Exception. _ init _ (self) self. length = length self. atleast = atleast try: s = raw_input ('enter something --> ') if len (s) <3: raise ShortInputException (len (s), 3) # Other work can continue as usual here exce Pt EOFError: print '\ nWhy did you do an EOF on me? 'Minimum t ShortInputException, x: print 'ShortInputException: The input was of length % d, \ was expecting at least % d' % (x. length, x. atleast) else: print 'no exception was raised. 'assert can trigger exceptions in program code with conditions and can be considered as conditional raise. remember: assert is almost always used to collect user-defined constraints, rather than capturing internal program design errors. Because Python automatically collects program design errors, it is usually necessary to write assert to capture events that exceed the index value, Type mismatch, and division of 0. The exception is AssertionError. If it is not captured by try, the program will be terminated. The statement format is assert <test>, <data> [python] def f (x): assert x> 0, 'X must be great zerot' return x ** 2 f (-1) 3. the built-in Exception class Python organizes the built-in exceptions into layers to support various capture modes Exception: the top-level root Super class of the Exception StandardError: the super class ArithmeticError of all built-in error exceptions: the super class OverflowError of all numerical errors: subclass [python] import exceptions help (exceptions) 4. Identify specific numeric errors. use the sys module to trace the last exception import systry: blockexcept: info = sys. exc_info () print info [0], ":", info [1], or in the following format: import sys tp, val, td = Sys. exc_info () sys. the return value of exc_info () is a tuple, (type, value/message, traceback) here, type ---- exception type value/message ---- exception information or the traceback parameter ---- the object that contains the call stack information. From this point, we can see that this method covers traceback. exercise: print the travel number and function name with exceptions. Use the raise prompt: [python] f = sys. exc_info () [2]. tb_frame.f_back f. f_code.co_name, f. f_lineno # function name line number sayHello [python] import sys www.2cto. comclass PrintNameLine (Exception): def _ init _ (self, say): Exception. _ init _ (self) self. sayhello = say try: raise PrintNameLine ('helloworld') failed t PrintNameLine, x: print '% s' % (x. sayhello)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.