Python Learning (eight) exceptions

Source: Internet
Author: User

8.1 What is an exception

8.2 Error in your own way

How to throw an exception, and create your own exception type.

8.2.1 Raise statements

Raise Exceptiontraceback (most recent):   " <pyshell#130> "  in <module>    raise  exceptionexception

Exception: The base class for all exceptions.

Attributeerror: Thrown when a property reference or assignment fails

IOError: Thrown when a nonexistent file (or other condition) is opened.

Indexerror: Raised when using an index that does not exist in the sequence.

Keyerror: Thrown when using a key that does not exist in the map.

Nameerror: Thrown when a name (variable) is not found.

SyntaxError: The code is syntactically wrong when it is thrown.

TypeError:

ValueError:

Zerodivisionerror: A divisor of 0 is thrown.

8.2.2 Custom Exception Classes

  Inherit from exception and you can.

  >>> class Somecustomexception (Exception)

8.3 Catching exceptions

If you want to catch an exception and want to do some processing, you can use Try/except

Try :     = input ('enter x')    = input ('enter y')     Print ((int) x/(int) y) except zerodivisionerror:     Print ('thesecond umber can not be zero! ')

After catching an exception, you can continue to throw an exception, using the Raise

8.4 More than one except clause

Multiple exceptions can be captured

Except XXX:

Xxxxx

Except YYY:

Fafafa

8.5 Capturing two exceptions with one block

  Try

...

Except (XXX, YYY,...)

...

8.6 Capturing objects

Try

...

EXCETPT (Zerodivisionerror, TypeError) as E://Catch an exception and print it out

...

8.7 Real Full capture

Catch all Exceptions:

Except://Do not declare exception type, catch all exceptions

....

88,000 Things

8.9 finally ....

Try

/ o

Except Nameerror:

Xxx

Else

Xxxx

Finally

Xxxx

8.10 Exceptions and functions

8.11 Unusual Zen

Python Learning (eight) 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.