Introduction to Python exception handling system

Source: Internet
Author: User

Python built-in exception Architecture
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

Capture exceptions

Method 1: capture all exceptions

'''First way to capture exceptions, capture all exceptions '''
Try:
A = B
B = c
Failed t Exception, data:
Print Exception, ":", data
'''Output: <type 'exceptions. exception'>: local variable 'B'
Referenced before assignment''

Method 2: Use the traceback module to view exceptions. Import the traceback module.

'''Second way to capture exceptions, use traceback to view exceptions '''
Try:
A = B
B = c
Except t:
Print traceback. print_exc ()
'''Output: Traceback (most recent call last ):
File "test. py", line 20, in main
A = B
UnboundLocalError: local variable 'B' referenced before assignmen

Method 3: Use the sys module to trace the final exception

'''Third way to capture exceptions, use the sys module to capture exceptions '''
Try:
A = B
B = c
Except t:
Info = sys. exc_info ()
Print info
Print info [0]
Print info [1]
''' Output:
(<Type 'exceptions. unboundlocalerror'>, UnboundLocalError ("local
Variable 'B' referenced before assignment ",),
<Traceback object at 0x00D243F0>)
<Type 'exceptions. unboundlocalerror'>
Local variable 'B' referenced before assignment
'''

Python exception system

Python Exception handling can accurately report error information to users. All exceptions are subclasses of the base Exception class. Custom exceptions are inherited from basic exceptions. Python automatically puts all built-in exceptions into the built-in namespace, so the program can use exceptions without importing the exceptions module.

Statement structure:

Method 1: Use the try and fail t statements to capture exceptions. There can be countless fail t statements to handle exceptions. If none of the Fail t statements are captured, then an exception is thrown to the function that calls this method for processing, until the system's main function is processed.

Note that when an exception is intercepted by multiple distinct T clauses, if there is an inheritance relationship between the exception classes, the subclass should be written in front, otherwise, the parent class directly intercepts the subclass exception. The sub-class exception that is placed below will not be executed.

try:
block
except [excpetion,[data...]]:
block
except [excpetion,[data...]]:
block
except [excpetion,[data...]]:
block

Method 2: Execute the else statement when no exception occurs.

try:
block
except  [excpetion,[data...]]:
block
else:
block

Method 3: The finally statement block will be executed no matter whether an exception occurs.

For example, if we open a file in python for read/write operations, I will close the file no matter whether an exception occurs during the operation.

try:
block
finally:
block

Method 4: try, try t, finally

try:
block
except:
block
finally:
block

Exception

Raise [exception [, data]

In Python, to cause an exception, enter the keyword raise, followed by the name of the exception to be thrown.

Exception names identify specific classes: Python exceptions are the objects of those classes. When a raise statement is executed, Python creates an object for the specified exception class.

The raise statement can also specify the initialization parameters for the exception object. Therefore, add a comma and a specified parameter (or a tuple consisting of parameters) after the name of the exception class ).

Example:

Try:
Raise MyError # throw an exception
Failed t MyError:
Print 'a error'

raise ValueError,’invalid argument’

The captured content is:

type  = VauleError
message = invalid argument

Other functions of Exception Handling

In addition to handling actual error conditions, there are many other functions for exceptions. A common usage in the standard Python library is to import a module and check whether it can be used.

Importing a module that does not exist will cause an ImportError exception. You can use this method to define multi-level functions-depending on which module is valid at runtime or supports multiple platforms (that is, platform-specific code is separated into different modules ).

You can also define your own exceptions by creating a class inherited from the built-in Exception class, and then use the raise command to raise your exceptions. If you are interested in this, please read more.

The following example demonstrates how to use exceptions to support specific platform functions. The Code comes from the getpass module, a encapsulation module that obtains the password from the user. The implementation of the obtained password on UNIX, Windows, and Mac OS platforms is different, but this Code encapsulates all the differences.

For example, platform-specific functions are supported.

# Bind the name getpass to the appropriate function

try:
import termios, TERMIOS                    
except ImportError:
try:
import msvcrt                          
except ImportError:
try:
from EasyDialogs import AskPassword
except ImportError:
getpass = default_getpass          
else:                                  
getpass = AskPassword
else:
getpass = win_getpass
else:
getpass = unix_getpass

Termios is a unique UNIX module that provides underlying control over input terminals.

If this module is invalid (because it is not on your system, or your system does not support it), the import fails, and Python triggers the ImportError exception.

OK, we don't have termios, so let's try msvcrt. It is a unique module in Windows and can provide an API for many useful functions in Microsoft Visual C ++ running services. If the Import fails,

Python will cause ImportError exceptions.

If the first two do not work, we try to import a function from EasyDialogs, which is a unique module of Mac OS and provides various types of pop-up dialog boxes. Once again, if the Import fails, Python will cause an ImportError exception that we captured.

None of these platform-specific modules are valid (probably because Python has been transplanted to many different platforms ), so we need to use a default password input function (this function is defined elsewhere in the getpass module ). Note what we have done here: we assign the default_getpass function to the variable getpass. If you read the official getpass document, it will tell you that the getpass module defines a getpass function. It does this: bind getpass to the correct function to adapt to your platform. Then, when you call the getpass function, you actually call the platform-specific function. This Code has already been set for you. You do not need to know or care about the platform on which your code is running. If you call getpass, it can always be handled correctly.

A try... limit t block can have an else clause, just like an if statement. If no exception is thrown in the try block, the else clause is executed. In this example, it means that if the import from EasyDialogs import AskPassword can work, we should bind getpass to the AskPassword function. Each Other try... example t block has a similar else clause. When we find that an import is available, we bind getpass to the appropriate function.

The custom Exception class inherits the Exception class and its subclass.

class MyError( ArithmeticError ):
pass

class MyError2 ( Exception ):
pass

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.