Exceptions for Python

Source: Internet
Author: User

I. Common forms of anomalies

An exception is an event that occurs during program execution and affects the normal execution of the program. In general, an exception occurs when Python does not handle the program properly. The exception is a Python object that represents an error. When a Python script exception occurs, we need to capture and process it, or the program terminates execution.

You can use the Try/except statement to catch an exception. The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it. If you do not want to end your program when an exception occurs, simply capture it in a try. The following is a simple syntax for try....except...else:

Try :< statements >        # Run other code except < name >:< statement >        # if the ' name ' exception is thrown in the try section except < name >,< data >:< statement >        # if the ' name ' exception is thrown, get additional data Else :< statement >        # If no exception occurs
Finally
< statements >

Try works by starting a try statement, and Python is tagged in the context of the current program so that when an exception occurs, it can go back here, the TRY clause executes first, and what happens next depends on whether an exception occurs at execution time.

    • If an exception occurs when the statement after the try is executed, Python jumps back to the try and executes the first except clause that matches the exception, and the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).
    • If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (This will end the program and print the default error message).
    • If no exception occurs when the TRY clause executes, Python executes the statement after the Else statement (if there is else), and then the control flow passes through the entire try statement.
    • Finally statement: Whether or not catch exception finally is the last need to execute.

Examples are as follows:

Try: A= 10b=0 A/bexceptException as E:Print(e)Print('Error')Else:    Print('This is ok!')finally:    Print('End') A= [1,2,4]Try:    Print(a[4])exceptIndexerror as E:Print(e)

Results:

Second, exception handling methods

Excepthion is all of the exception base classes (), for Python standard exceptions, we listed below for reference:

Exception name

Describe

Baseexception

base class for all exceptions

Systemexit

Interpreter Request exited

Keyboardinterrupt

User interrupt execution (usually input ^c)

Exception

base class for general errors

Stopiteration

There are no more values for iterators

Generatorexit

Generator (generator) exception occurred to notify exit

StandardError

Base class for all built-in standard exceptions

Arithmeticerror

base class for all numeric calculation errors

Floatingpointerror

Floating-point calculation error

Overflowerror

Numeric operation exceeds maximum limit

Zerodivisionerror

Except (or modulo) 0 (all data types)

Assertionerror

Assertion statement failed

Attributeerror

Object does not have this property

Eoferror

No built-in input, EOF Mark reached

EnvironmentError

Base class for operating system errors

IOError

Input/output operation failed

OSError

Operating system error

Windowserror

System call failed

Importerror

Failed to import module/object

Lookuperror

base class for invalid data queries

Indexerror

This index is not in the sequence (index)

Keyerror

This key is not in the map

Memoryerror

Memory overflow error (not fatal for Python interpreter)

Nameerror

Object not declared/initialized (no attributes)

Unboundlocalerror

To access uninitialized local variables

Referenceerror

Weak references (Weak reference) attempt to access objects that have been garbage collected

RuntimeError

General run-time errors

Notimplementederror

Methods that have not been implemented

SyntaxError

Python syntax error

Indentationerror

Indentation Error

Taberror

Tab and Space Mix

Systemerror

General Interpreter system error

TypeError

An operation that is not valid for type

ValueError

Invalid parameter passed in

Unicodeerror

Unicode-related errors

Unicodedecodeerror

Error in Unicode decoding

Unicodeencodeerror

Unicode encoding Error

Unicodetranslateerror

Unicode Conversion Error

Warning

Base class for warnings

Deprecationwarning

Warnings about deprecated features

Futurewarning

Warning about the change in the construction of future semantics

Overflowwarning

Old warning about auto-promotion to Long integer

Pendingdeprecationwarning

Warnings about attributes that will be discarded

Runtimewarning

Warning for suspicious run-time behavior (runtime behavior)

Syntaxwarning

Warning of suspicious syntax

Userwarning

Warnings generated by user code

Third, the use of raise keywords

The raise statement is used to trigger an exception with the following syntax:

Raise [Exception [, Args [, Traceback]]

The type of exception in the statement is an exception (for example, the Nameerror) parameter is an exception parameter value. This parameter is optional and if not provided, the exception parameter is "None". The last parameter is optional (rarely used in practice) and, if present, is the tracking exception object.

Examples of procedures are as follows:

Try: A= 10b=0 A/bexceptException as E:Print(e)Print('Error')    RaiseeElse:    Print('This is ok!')finally:    Print('End')Print('Hello')

Results:

Exceptions for Python

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.