Python Errors and exceptions

Source: Internet
Author: User
Tags throw exception

Try...except...finally

The remaining statement after the occurrence of the exception in the TRY statement block never arrives (and therefore never executes). Once an exception is thrown, you must decide where the control flow will arrive next. The remaining code will be ignored, the interpreter will search the processor and, once found, start executing the code in the processor.
If the appropriate processor is not found, then the exception is handed over to the caller, which means that the stack frame immediately returns to the previous one. If the corresponding processor is not found on the upper-level caller, the exception will continue to be forwarded upward until the appropriate processor is found. If the corresponding processor is still not found at the top level, the exception is considered unhandled, and the Python interpreter displays a trace return message and exits.

PS: Avoid putting large pieces of code into try-except and using pass to ignore errors. You can catch specific exceptions and ignore them, or catch all exceptions and take specific actions. Do not catch all exceptions, and then ignore them.

Try:    Print 'Try ...'R= 10/0Print 'Result:', RexceptZerodivisionerror, E:Print 'except:', Efinally:    Print 'finally ...'Print 'END'

The exception parameter E is a class instance that contains diagnostic information from the code that caused the exception. Print except: ', E is actually called the __str__ method of E.

If you just want to return this information, you can use STR ().

def Safe_float (object):     Try :         = Float (object)    except  (ValueError, TypeError), diag:        = Str (DIAG)     return retval

With and context management

Reference links: Talking about Python with statements

The WITH statement is an alternative to the try/finally encoding paradigm for controlling access to resources.
The WITH statement is useful for accessing resources, ensuring that the necessary "cleanup" operations are performed regardless of whether an exception occurs during use, freeing up resources such as automatic shutdown after file use, automatic acquisition and release of locks in threads, and so on.

Usage of the WITH statement

With context_expression [as Target (s)]:    with-body

Custom Context Manager

ONTEXT_MANAGER.__ENTER__ (): Enters the context manager's run-time context and is called before the statement body executes. If an AS clause is specified, the WITH statement assigns the return value of the method to the target in the AS clause.

Context_manager.__exit__ (Exc_type, Exc_value, Exc_traceback): Exits the run-time context associated with the context manager, which returns a Boolean value indicating whether the exception that occurred is being processed. Exc_type, Exc_value, the Exc_traceback parameter represents the exception that caused the exit operation, and if no exception occurred when exiting, none of the 3 parameters. When an exception occurs, if you do not want to handle the exception, set the function return value to True, and if you want to handle the exception, you only need to set the return value to False (do not display the re-throw exception, that is, do not re-throw the exception passed in by the parameter). The context management code then detects whether __exit__ () fails to handle the exception and re-throws the exception after exiting the method to be handled by code logic other than the WITH statement. (PS: If an exception is generated inside the method, it supersedes the exception generated by the statement in Statement-body. )

classDummyresource:def __init__(self, Tag): Self.tag=TagPrint 'Resource [%s]'%Tagdef __enter__(self):Print '[Enter%s]: Allocate resource.'%Self.tagreturnSelf#can return different objects    def __exit__(self, exc_type, Exc_value, EXC_TB):Print '[Exit%s]: free resource.'%Self.tagifExc_tb isNone:Print '[Exit%s]: Exited without exception.'%Self.tagElse:            Print '[Exit%s]: Exited with exception raised.'%Self.tagreturnFalse#can be omitted, the default of none is also seen as false</span>With Dummyresource ('Normal'):    Print '[With-body] Run without exceptions.'----------------------------------------------------Resource [Normal] [Enter Normal]: Allocate Resource. [ with-body]    Run without exceptions.    [Exit Normal]: free resource. [Exit Normal]: Exited without Exception.with Dummyresource ('with-exception'):    Print '[With-body] Run with exception.'    RaiseExceptionPrint '[With-body] Run with exception. Failed to finish statement-body!'--------------------------Resource [ with-Exception] [Enter with-Exception]: Allocate resource. [ with-body]    Run with exception. [Exit with-Exception]: free resource. [Exit with-Exception]: Exited with Exception raised. Traceback (most recent): File"G:/demo", line 20,inch<module>RaiseException Exception
As you can see, normal execution executes the statement body With-body first, and then executes the __exit__ () method to free the resource. With-body does not complete when an exception occurs in With-body, but the resource is guaranteed to be freed, and the resulting exception is caught by code logic outside the WITH statement.

Raise throwing errors

Define our own error types only when necessary. If you can choose a built-in error type that Python already has (such as valueerror,typeerror), use the Python built-in error type as much as possible.

class Fooerror (standarderror):     Pass def Foo (s):     = Int (s)    if n==0:        raise fooerror ('Invalid value:% s' % s)    return 10/n

assert
def Foo (s):     = Int (s)    assert'n is zero! '    # The assert means that the expression n! = 0 should be true, otherwise the subsequent code will go wrong.     return / ndef  Main ():    foo ('0 ')

Common error types and inheritance relationships

baseexception+--Systemexit+--Keyboardinterrupt+--Generatorexit+--Exception+--stopiteration+--StandardError| +--Buffererror| +--Arithmeticerror|    | +--Floatingpointerror|    | +--Overflowerror|    | +--Zerodivisionerror| +--Assertionerror| +--Attributeerror| +--EnvironmentError|    | +--IOError|    | +--OSError|         | +--windowserror (Windows)|         | +--vmserror (VMS)| +--Eoferror| +--Importerror| +--Lookuperror|    | +--Indexerror|    | +--Keyerror| +--Memoryerror| +--Nameerror|    | +--Unboundlocalerror| +--Referenceerror| +--RuntimeError|    | +--Notimplementederror| +--SyntaxError|    | +--Indentationerror|         | +--Taberror| +--Systemerror| +--TypeError| +--ValueError| +--Unicodeerror| +--Unicodedecodeerror| +--Unicodeencodeerror| +--Unicodetranslateerror+--Warning+--deprecationwarning+--pendingdeprecationwarning+--runtimewarning+--syntaxwarning+--userwarning+--futurewarning+--importwarning+--unicodewarning+--byteswarning

2015-05-27

Python Errors and exceptions

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.