Python Error and exception concepts

Source: Internet
Author: User

This article shares with you the main isPythoncommon mistakes and exceptions and how to deal with them, let's take a look at it and hope toLearningPython has helped. 1. How errors and exceptions are handled 1. Common Mistakes 1. A:Nameerror 2. If True:SyntaxError 3. F = OEPN (' 1.txt '):IOError 4.10/0:Zerodivisionerror 5. A = Int (' d '):ValueError 6.program run Interrupt:Keyboardinterrupt 2.python- Handling Exceptions using try_except (1) Try: Try_suiteexceptException [E]: Exception_block 1. Tryused to captureTry_suitethe error in,and give the error toexceptprocessing 2. Exceptused to handle exceptions,If handling exceptions and setting catch exceptions are consistent,UseException_blockHandling Exceptions # case 1Try: Undefexcept: Print' Catch an except ' # case 2Try: ifUndefexcept: Print' Catch an except ' · Case1: Can catch exception because it is a run-time error · Case2: Cannot catch exception because it is a syntax error, pre-run error -- # Case 3Try: UndefexceptNameerror,e: Print' Catch an except ', E # Case 4Try: UndefexceptIoerror,e: Print' Catch an except ', E · Case3: You can catch exceptions because the settings captureNameerrorException · Case4: Cannot catch exception because the settingIOError, will not processNameerror Example ImportRandom num = random.randint (0, 100) whileTrue: Try: guess = Int (raw_input ("Enter 1~100")) Except ValueError, E: Print "Enter 1~100" Continue ifGuess > num: Print "Guess bigger:", guess Elif Guess < num: Print "Guess Smaller:", guess Elif guess = = num: Print "Guess ok,game over" Break print ' \ n ' 3. Python handles exceptions using try_except (2) · Try-except: Handling Multiple exceptions Try: Try_suiteexceptException1[e]: Exception_block1exceptException2[e]: Exception_block2exceptExceptionn[e]: Exception_blockn 4. python-try_finally use Try: Try_suitefinally: Do_finally ·ifTrystatement does not catch error, code executiondo_finallyStatement ·ifTryThe statement captures the error and the program first executesdo_finallystatement, and then give the captured error to thepythonInterpreter Processing 5. Python-try-except-else-finally Try: Try_suite except: Do_except finally: Do_finally ·ifTryThe statement does not catch an exception and executesTrycode snippet, executefinally ·ifTrycatch exception, first executeexcepthandle the error, and then executefinally 6. Python-with_as Statements withContext[ASvar]: With_suite · Withstatement to replaceTry_except_finallstatement to make the code more concise · Contextexpression Return is an object · Varused to saveContextreturns an object, a single return value, or a meta-ancestor · With_suiteUsevarvariable toContextreturning an object for action The With statement is essentially context management : 1.Context Management Protocol: Containment Method__enter__ ()and the__exit()__ ,The object that supports this protocol is to implement both methods 2.Context Manager: Define execution withstatement is the runtime context to be established, which is responsible for executing the withentry and exit operations in the context of a statement block 3.into the context Manager: Call Manager__enter__method, if you set theas Varstatement,varVariable Acceptance__enter__ ()method return value 4.Exit Context Manager: Call Manager__exit__Method classMycontex(object): def__init__(self, name): Self.name = Name def__enter__(self): Print"__enter__" returnSelf defdo_self(self): Print"Do_self" def__exit__(Self, Exc_type, Exc_val, EXC_TB): Print"__exit__" Print"Error:", Exc_type, "info:", exc_val if__name__ = = "__main__": withMycontex (' Test context ') asF: PrintF.name F.do_self () whith Statement Application scenario: 1.file Operations 2.mutually exclusive objects, such as mutexes, between process threads 3.other objects that support context 2. standard exception and automatic with exception 1. Python-assert and raise statements · RaisStatement · Reisestatements are used to actively throw exceptions ·syntax Format:Raise[exception[,args]] · exception: Exception class · Args: A tuple that describes the exception information RaiseTypeError, ' Test Error ' RaiseIOError, ' File not Exit ' · AssertStatement ·Assertion Statement:assertstatement is used to detect whether an expression is true, if false, to throwAssertionerrorError ·syntax Format:assert Expression[,args] · Experession: An expression · Args: The descriptive information of the judging condition Assert 0, ' test assert ' Assert 4==5, ' Test assert ' 2. python- Standard exceptions and custom exceptions ·Standard Exceptions · Pythonbuilt-in exceptions that existed before the program was executed · ·Custom Exceptions: · Pythonallow custom exceptions to describepythonNo exceptions are involved in the ·custom exceptions must inheritExceptionclass ·custom exceptions can only be triggered proactively classCustomerror(Exception): def__init__(self, info): Exception.__init__ (self) Self.message = info PrintID (self) def__str__(self): return' custionerror:%s '% self.message Try: RaiseCustomerror (' Test customerror ')exceptCustomerror, E: Print' errorinfo:%d,%s '% (ID (e), E) Source:Blog Park

Python Error and exception concepts

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.