Python Standard Exception Summary

Source: Internet
Author: User
Tags class definition finally block throw exception

before we write Script or There are always a lot of anomalies and errors in the process of software development, and Python has two very important functions that can handle exceptions and any unexpected error , these two functions are exception handling and assertion.

Exception handling: Mainly includes syntax errors and other standard exceptions, the standard exceptions are described in the following table.

Assertion: An assertion is a sanity check that you can turn on or off when the program's test is complete. The simplest way to assert is to compare it to a raise-if statement (or, more precisely, to add a raise-if-not declaration). An expression is tested, and if the result appears false, an exception is thrown. Assertions are keywords that are used in the Python1.5 version by ASSERT statements, new keywords in python.

Programmers often place assertions to check for input validity, or check for valid output after a function call.

First, the standard exception table

Exception name

Description
Exception

base class for all exceptions

Stopiteration

Thrown when the next () method of an iterator does not point to any object

Systemexit

Thrown by the Sys.exit () function

StandardError

In addition to stopiteration exceptions and Systemexit, the base class for all built-in exceptions

Arithmeticerror

base class for all errors that occur in numerical calculations

Overflowerror

When the number type calculation exceeds the maximum limit raised

Floatingpointerror

triggered when a floating-point operation fails

Zerodivisonerror

When all numeric type operations are thrown except operations or modulo zeros

Assertionerror

Thrown when an assertion statement fails

Attributeerror

Thrown when a property reference or assignment fails

Eoferror

Triggered when the end of the file is reached from input () function

Importerror

triggered when an import statement fails

Keyboardinterrupt

When the user interrupts the program execution, it is usually triggered by pressing CTRL + C

Lookuperror

All Lookup error base class

Indexerror

Keyerror

Thrown when an index is not found in a sequence

Thrown when the specified key is not found in the dictionary

Nameerror

When an identity that is not found in the local or global namespace is raised

Unboundlocalerror

EnvironmentError

Thrown when an attempt is made to access a local variable in a function or method, but no value is assigned to it.

The base class for all exceptions that occur outside of the Python environment.

IOError

IOError

thrown When an input/output operation fails, such as a print statement or an open () function that attempts to open a nonexistent file

An operating system-related error is raised

SyntaxError

Indentationerror

When a syntax error in Python is thrown;
indentation thrown is not specified correctly.

Systemerror

When the interpreter finds an internal problem, but encounters this error, the Python interpreter does not exit the thrown

Systemexit thrown when the Python interpreter does not use the Sys.exit () function. If the code is not processed, the interpreter exits.

Thrown when an action or function is invalid on a specified data type

ValueError thrown when a built-in function is a valid type for a data type, parameter , But the parameter specifies an invalid value
RuntimeError

Thrown when a generated error does not belong to any category

Notimplementederror

This exception is thrown when the abstract method is not actually implemented when it is to be implemented in an inherited class

Exception Example:

1, Filenotfounderror try to open the text D:\\openstack.txt file because the file does not exist will be reported Filenotfounderror:f=open ("D:\\openstack.txt") Traceback   (most recent call last):  file  "<pyshell#0>",  line 1,  in <module>    f=open ("D:\\openstack.txt") FileNotFoundError: [Errno  2] No such file or directory:  ' D:\\openstack.txt ' 2, Zerodivisionerror division or modulo operation, where divisor is zero  >>> 5/0Traceback  (most recent call  Last):  file  "<pyshell#1>", line 1, in <module>     5/0zerodivisionerror: division by zero3, Importerror is generally in the import module, because the module does not exist and other reasons cause error >> > import  wwwwTraceback  (most recent call last):  file  " <pyshell#2> ", line 1, in <module>    import   Wwwwimporterror: no module named&nBSP; ' Wwww ' 4, valueerror  is generally due to the data type of the incoming parameters error caused by errors.  >>> a= "Sterc" >>> int (a) traceback  (most recent call last) :  file  "<pyshell#4>", line 1, in <module>     int (a) valueerror: invalid literal for int ()  with base 10:  ' Sterc ' >>>

二、异常处理

  python中包含两种异常处理语句,可以使用try...except...finally或者try...except..else语句来处理异常,接下来简单的介绍两种语句的语法以及两者的区别:

Try statement principle:

First, execute the TRY clause (the statement between the keyword try and the keyword except)

If no exception occurs, the EXCEPT clause is ignored, and the try clause finishes after execution.

If an exception occurs during the execution of a try clause, the remainder of the try clause is ignored. If the type of the exception matches the name after except, then the corresponding except clause is executed. The code after the last try statement is executed.

If an exception does not match any of the except, then the exception is passed to the upper try.

A try statement may contain multiple except clauses that handle different specific exceptions. Only one branch will be executed at most.

The handler will handle only the exceptions in the corresponding try clause, not the exceptions in the other try handlers.

A except clause can handle multiple exceptions at the same time, and these exceptions will be placed in parentheses as a tuple.


try...except. else syntax :

TRY:&NBSP;&NBSP;&NBSP;YOU&NBSP;DO&NBSP;YOUR&NBSP;OPERATIONS&NBSP;HERE&NBSP;&NBSP;&NBSP, ....... ......... except exceptioni:   if there is exceptioni, then execute  This block.except exceptionii:   if there is exceptionii, then  execute this block.   ......................else:   If  there is no exception then execute this block.     Single The  try  statement can have more than one except statement.   When  try  blocks contain exception declarations that may throw different types, this is useful, and you can also provide a generic  except  clause to handle exceptions (not advocating) except clauses, which can include  else   clauses.   If the code is in try: The block does not throw an exception then the code in the  else  block execution else is the code that can run the normal part of the exception, which does not require the  try:  block protection   try:    fh = open ("Testfile",  "w+")    fh.write ("this is my  test file for exception handling!! ") Except ioerror:   print  ("error: can\ ' T find file or read data") else:   print   ("written content in the file successfully")    fh.close ()       after normal execution, the contents of the Testfile file will be generated: this is my test file for exception  handling!   the console output results are as follows:  written content in the file  Successfully

Handling multiple exceptions with the EXCEPT clause

Just now our example is dealing with one type of exception, while except can handle multiple types of exceptions, such as

Except (Valueerror,importerror,runtimeerror) it is possible to write multiple types of standard errors into a tuple, but it is difficult to make a type of error analysis for our team type easily.

TRY:FH = open ("Testfile", "R") Fh.write ("This was my test file for exception handling!!") Except (Valueerror,importerror,runtimeerror): Print ("error:can\ ' t find file or read data") Else:print ("Written cont ENT in the file successfully ") Fh.close () Result: Error:can ' t find file or read data #这里没有报出是那个类型的标准错误.
try-finally clause:

Use try: block. The finally block is mandatory, regardless of whether the try block throws an exception or not. The syntax for the try-finally statement is this.

Try:you do your operations here;   ...................... Due to any exception, this is may skipped.

Except Exceptioni:if there is Exceptioni and then execute this block.except exceptionii:if there are exceptionii, then E Xecute this block.

Finally

This would always be executed.

try...except...finally无论try块能否正常的执行,finally是一定会执行的模块。

TRY:FH = open ("Testfile", "R") Fh.write ("This was my test file for exception handling!!") Except (Valueerror,importerror,runtimeerror): Print ("error:can\ ' t find file or read data") Finally:print ("written c Ontent in the "successfully") Fh.close () #关闭文件 Result: No content was written in the file, the console outputs the following: Error:can ' t find file or read Datawritten Content in the file successfully

Throw exception

You can trigger several aspects of an exception by using the Raise statement. The general syntax for the raise statement is as follows.

Grammar
raise [Exception [, Args [, Traceback]]

Here, Exception is the parameter value of the exception type (for example, nameerror) argument is an exception. The parameter is optional, and if not provided, the exception parameter is none.

The last parameter, Traceback, is also optional (rarely used in practice) and, if present, is a backtracking object for the exception.

Example

An exception can be a string, a class, or an object. Most python's exception core is the exception that triggers the class exception, using an instance parameter of the class. It is easy to define a new exception, which can be done as follows-

def functionname (level): If level <1:raise Exception (level) # The code below to this would not being E Xecuted # If we raise the exception return level

Note: In order to catch an exception, a "except" statement must be an exception that indicates a thrown class object or a simple string exception. For example, to catch an exception above, we must write the EXCEPT clause as follows--

Try:business Logic here...except Exception as e:exception handling here using e.args...else:rest of the code here ...

The following example shows how to use the trigger exception:

#!/usr/bin/python3def functionname: If level <1:raise Exception (level) # The code below to T His would is executed # if we raise the exception return Leveltry:l=functionname ( -10) print ("Level=" , l) except Exception as E:print ("Error in level argument", E.args[0])

This will produce the following results

Error in Level argument-10

User-defined exceptions

In Python, you can also create your own exceptions by using the built-in exception standard derived class.

Here is an example of a runtimeerror. Here a class is created, which is a subclass of RuntimeError. When needed, an exception can be captured to display more specific information, which is useful.

In the try block, the user-defined exception is thrown and clipped in the except block. The variable e is an instance of the Networkerror class that is used to create a network error.

Class Networkerror (RuntimeError): Def __init__ (self, arg): Self.args = arg

So after the above class definition, you can throw an exception as follows-

Try:raise networkerror ("bad hostname") except Networkerror,e:print E.args




This article is from the "Keep Dreaming" blog, please be sure to keep this source http://dreamlinux.blog.51cto.com/9079323/1911106

Python Standard Exception Summary

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.