Python error and Exception learning notes

Source: Internet
Author: User
Tags throw exception

error and Exception ConceptsError: 1. Syntax error: The code does not conform to the interpreter or compiler Syntax 2. Logic error: Incomplete or illegal input or the calculation of a problem exception: during the execution of the body caused the program cannot execute 1. The program encountered a logic or algorithm problem 2. Computer errors during operation (insufficient memory or IO error Mistaken error and exception differencesError: Syntax or logic error before code is run, syntax error is modified before execution, logic error cannot modify exception is divided into two steps: 1. Exception generation, check to error and interpreter is considered abnormal, throw exception; 2. exception handling, intercept exception, ignore or terminate program handling exception python Common errorsCommon error: Ipython under 1. A:nameerror directly refers to 2 without defining a variable. If True:syntaxerror syntax error 3. f = open (' 1.txt '): IOError attempts to open a nonexistent file at the time of 4. 10/0: Zerodivisionerror 5. a = Int (' DD '): An error encountered when forcing type conversion by ValueError try--except exception Handling (1)Try-except: Exception HandlingTry:Try_suiteexcept Exception [, E]:Exception_block1.try is used to capture errors in Try_suite, and the error is given to except processing 2.except to handle exceptions, if exception handling and set catch exceptions are consistent, use Exception_block to handle exception examples:Try:aexcept Exception, E:Print eTry-except Capture Exception Analysis: Case 1:try:undefexcept:print ' catch a except ' Case 2:try:if Undefexcept:print ' catch an E Xcept ' Case 1: Exception can be caught because it is a run-time error: The exception is not caught because it is a syntax error, a pre-run error case 3:try:undefexcept Nameerror, E:print ' catch-an except ' , Ecase 4:try:undefexcept IOError, E:print ' catch an except ', Ecase 3: Exceptions can be caught because the settings catch Nameerror exception Case 4: Exception cannot be caught because setting IO Error, will not handle nameerror try--except exception Handling (2)Try-except: Handling multiple exceptions try:try_suiteexcept Exception1 [E]: Exception_block1except Exception2 [E]: Exception_block2exce    PT Exceptionn [E]: exception_blockn try-except--else using try:try_suiteexcept Exception1 [E]: Exception_block1else: None_exception If there is no exception, execute the code in the Else statement try--finally StatementsTry-finally statement: Try:try_suitefinally:do_finally1. If the try statement does not catch an error, the code executes the Do_finally statement 2. If the try statement catches an error, the program executes the do_finally statement first. The captured error is then handed to the Python interpreter to handle the try-finally statement: rule: Try-finally performs a finally code action regardless of whether an exception is detected: Provides a cleanup mechanism for exception handling events, Use to close files or release system resources try-except-finally: Try:try_suiteexcept:do_exceptfinally:do_finally1. If the try statement does not catch an exception, after executing the try code snippet, execute Finally2. If try catches an exception, the except processing error is performed first, and then finallytry-except-else-finally is used: try:try_suiteexcept:do_exceptelse:do_els Efinally:do_finally1. If the try statement does not catch an exception, after executing the try block, execute the Else code block, and finally execute the finally2. If the try catches an exception, the except processing error is performed first, and then the finally With statementWith statement: with context [as Var]: With_ The Suite1.with statement is used in place of the try-except-finally statement, which is more concise; the 2.context expression returns an object, 3.var is used to hold the context return object, a single return value, or a meta-ancestor; 4.with_ Suite uses the Var variable to manipulate the context return object ... (Talking about what a dog poo!!!) ) Raise and AssertThe Raise statement raise statement is used to actively throw exception syntax formats: raise [Exception [, Args]]exception: Exception class args: tuple example describing exception information: Raise Typeerrorraise TypeError, ' Test error ' raise IOError, ' File not Exist ' Assert statement assertion statement: Assert statement is used to detect whether an expression is true or false to raise a assertionerror error; Syntax format: Assert expression [, args]expression: Expression args: A descriptive example of a condition: Assert 7==6assert 0, ' Test Error ' python Standard and custom exceptionsStandard exception: Python built-in exception, A custom exception already exists before the program executes: 1.python allows custom exceptions to describe exceptions that are not covered in Python 2. Custom exceptions must inherit the exception Class 3. Custom exceptions can only be actively triggered by the custom exception example: Class Fileerror ( IOError): Passraise fileerror, ' Test Fileerror ' class Customerror (Exception): Def __init__ (self, info): EXCEP Tion.__init__ (self) self.errorinfo = info def __str__ (self): Return ' customerror:%s '% self.errorinfotry : Raise Customerror (' Test customerror ') except Customerror, E:print ' Error Info:%s '% E

Python error and Exception learning notes

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.