Python3 exception detection and Python3 Detection

Source: Internet
Author: User

Python3 exception detection and Python3 Detection
1. Standard exceptions

AssertionError

Assert failure

AttributeError

Attempt to access unknown object properties

EOFError

Mark at the end of the user input file: EOF (Ctrl + d)

FloatingPointError

Floating Point Calculation Error

GeneratorExit

When the generator. close () method is called

ImportError

When the import module fails

IndexError

The index is out of the range of the sequence.

KeyError

Search for a non-existent keyword in the dictionary

KeyboardInterrupt

User input interrupt key (Ctrl + c)

MemoryError

Memory overflow (memory can be released by deleting objects)

NameError

Try to access a non-existent variable

NotImplementedError

Unimplemented Methods

OSError

Operating system exceptions (for example, opening a non-existent file)

OverflowError

The value operation exceeds the maximum limit.

ReferenceError

Weak reference attempts to access an object that has been recycled by the garbage collection mechanism.

RuntimeError

General running errors

StopIteration

The iterator does not have more values.

SyntaxError

Python syntax error

IndentationError

Indentation Error

TabError

Mixed Use of Tab and Space

SystemError

Python Compiler System Error

SystemExit

The Python compiler process is disabled.

TypeError

Invalid operation between different types

UnboundLocalError

Access an uninitialized local variable (subclass of NameError)

UnicodeError

Unicode errors (subclass of ValueError)

UnicodeEncodeError

Unicode encoding error (subclass of UnicodeError)

UnicodeDecodeError

Unicode decoding error (subclass of UnicodeError)

UnicodeTranslateError

Unicode Conversion error (subclass of UnicodeError)

ValueError

Invalid parameter passed in

ZeroDivisionError

Division zero

2. built-in exception class hierarchy


BaseException
+ -- SystemExit
+ -- KeyboardInterrupt
+ -- GeneratorExit
+ -- Exception
+ -- StopIteration
+ -- ArithmeticError
| + -- FloatingPointError
| + -- OverflowError
| + -- ZeroDivisionError
+ -- AssertionError
+ -- AttributeError
+ -- BufferError
+ -- EOFError
+ -- ImportError
+ -- LookupError
| + -- IndexError
| + -- KeyError
+ -- MemoryError
+ -- NameError
| + -- UnboundLocalError
+ -- OSError
| + -- BlockingIOError
| + -- ChildProcessError
| + -- ConnectionError
| + -- BrokenPipeError
| + -- ConnectionAbortedError
| + -- ConnectionRefusedError
| + -- ConnectionResetError
| + -- FileExistsError
| + -- FileNotFoundError
| + -- InterruptedError
| + -- IsADirectoryError
| + -- NotADirectoryError
| + -- PermissionError
| + -- ProcessLookupError
| + -- TimeoutError
+ -- ReferenceError
+ -- RuntimeError
| + -- NotImplementedError
+ -- SyntaxError
| + -- IndentationError
| + -- TabError
+ -- SystemError
+ -- TypeError
+ -- ValueError
| + -- UnicodeError
| + -- UnicodeDecodeError
| + -- UnicodeEncodeError
| + -- UnicodeTranslateError
+ -- Warning
+ -- DeprecationWarning
+ -- PendingDeprecationWarning
+ -- RuntimeWarning
+ -- SyntaxWarning
+ -- UserWarning
+ -- FutureWarning
+ -- ImportWarning
+ -- UnicodeWarning
+ -- BytesWarning
+ -- ResourceWarning

3. Exception Handling 1. try statement

Try:

Detection scope

Failed t Exception [as reason]:

Code after Exception Processing

 

There can be a combination of multiple consumer T and try, because the detection range will certainly produce multiple exceptions, you can use multiple consumer T and try combinations to focus on exceptions of interest.

You can use () to enclose multiple exceptions that need to be processed in the same way after handling multiple types of exceptions.

try:
     int ('abc')
     sum = 1 + '1'
     f = open ('I am a non-existing document.txt')
     print (f.read ())
     f.close ()
except (OSError, ValueError, TypeError) as reason:
     print ('Error T_T \ nThe reason for the error is:' + str (reason))
2. try finally statement

Try:

Detection scope

Failed t Exception [as reason]:

Code after Exception Processing

Finally:

Something to do (for example, you can close the file here after an error occurs)

try:
     f = open ('My_File.txt') # The file "My_File.txt" does not exist in the current folder T_T
     print (f.read ())
except OSError as reason:
     print ('Error:' + str (reason))
finally:
     if 'f' in locals (): # If the file object variable exists in the current local variable symbol table, it means that the opening was successful
         f.close ()
3. raise Statement (throwing an exception)

Raise Exception name

try:
     for i in range (3):
         for j in range (3):
             if i == 2:
                 raise KeyboardInterrupt
             print (i, j)
except KeyboardInterrupt:
     print ('Exit!') 

 


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.