Python--exception handling--12

Source: Internet
Author: User
Tags define function finally block python script

Python Exception Handling

Original blog, reprint please indicate the Source--Zhou Xuewei http://www.cnblogs.com/zxouxuewei/

Python provides two very important features to handle the exceptions and errors that Python programs run in. You can use this feature to debug a python Program.

    • Exception handling: This site Python tutorial will be described in Detail.
    • Assertion (assertions): This site Python tutorial will be described in Detail.

Python Standard exception

Exception name

Description
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
what is an exception?

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.

Exception Handling

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.

Grammar:

The following is a simple syntax for try....except...else :

Try :< statement >        < name >:< statement >        #如果在try部份引发了'name' < name >,< data >:< statement > #如果引发了 ' name '          exception, get Additional data Else :< 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.
Instance

Here is a simple example that opens a file where the contents of the file are written and the exception does not occur:

#!/usr/bin/python#-*-coding:utf-8-*-Try: FH= Open ("testfile","W") Fh.write ("This is a test file for testing exceptions !") except Ioerror:print"Error: failed to find file or read file"Else: Print"content written to file succeeded"fh.close () above program output: $ python test.py content written to file successfully $ cat testfile # View written content This is a test file that is used to test for exceptions!!
Instance

Here is a simple example that opens a file where the contents of the file are written, but the file does not have write permission, and an exception occurs:

#!/usr/bin/python#-*-coding:utf-8-*-Try: FH= Open ("testfile","W") Fh.write ("This is a test file for testing exceptions !") except Ioerror:print"Error: failed to find file or read file"Else: Print"content written to file succeeded"Fh.close () before executing the code for testing convenience, we can first remove the Testfile file write permission, the command is as Follows: chmod-W testfile Execute the above code: $ python test.py Error: failed to find file or read file
use except without any exception type

You can use except without any exception type, as in the following example:

Try :    normal operation   ... except: an    exception occurred, execute the code   .................... .............. Else :    If there is no exception to execute this piece of code

The try-except statement above captures all occurrences of the Exception. But this is not a good way to identify specific exception information through the Program. Because it catches all the exceptions.

using except with multiple exception typestry-finally statements

The try-finally statement executes the final code regardless of whether an exception Occurs.

Try:< statements >finally:< statements >#退出try时总会执行raise实例 #!/usr/bin/python#-*-coding:utf-8-*-Try: FH= Open ("testfile","W") Fh.write ("This is a test file for testing exceptions !")finally: Print"Error: failed to find file or read file"If the open file does not have writable permissions, the output is as Follows: $ python test.py Error: failed to find file or read file

The same example can be written in the following way:

#!/usr/bin/python#-*-coding:utf-8-*-Try: FH= Open ("testfile","W")    Try: Fh.write ("This is a test file for testing exceptions !")    finally: Print"Close File"fh.close () except Ioerror:print"Error: failed to find file or read file"

Executes the finally block code immediately when an exception is thrown in the try Block.

After all the statements in the finally block are executed, the exception is triggered again, and the except block code is Executed.

The contents of the parameter differ from the Exception.

parameter of the exception

An exception can take a parameter that can be used as the output exception information Parameter.

You can use the except statement to catch the parameters of the exception, as Follows:

Try :    normal operation ...   except exceptiontype, Argument:    You can output the value of Argument in this ...!!!!!!!!!

The exception value that the variable receives is usually contained in the Exception's Statement. In a Tuple's form, a variable can receive one or more Values.

Tuples typically contain error strings, error numbers, and error locations.

Instance

The following is an instance of a single exception:

#!/usr/bin/python#-*-coding:utf-8-*-# define function def temp_convert (var):    Try:        return int(var) except valueerror, argument:print"parameter does not contain a number \ n", argument# calls the function Temp_convert ("XYZ"); The above program execution results are as follows: the $ python test.py parameter does not contain a digital invalid literal for int() withBase Ten:'XYZ'
Triggering an exception

We can use the raise statement to trigger the exception ourselves

The raise syntax format is as Follows:

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.

Instance

An exception can be a string, a class, or an object. The Python kernel provides exceptions, most of which are instantiated classes, which are parameters of an instance of a class.

It is very simple to define an exception as Follows:

def functionname (level):     if 1 :        Raise Exception ("Invalid level! " , Level)        # After the exception is triggered, the following code will no longer execute

note: to be able to catch exceptions, The "except" statement must have the same exception to throw the class object or String.

For example, we capture the above exception, and the "except" statement looks like this:

Try :     " Invalid level! " :    Trigger Custom Exception     else: The    rest of the code
Instance
#!/usr/bin/python#-*-coding:utf-8-*-# define function def Mye (level):ifLevel <1: Raise Exception ("Invalid level!", Level) # After the exception is triggered, the following code will no longer executeTry: Mye (0)//triggering an exceptionExcept"Invalid level!": Print1Else: Print2Execute the above code, the output is: $ python test.py Traceback (most recent call last): File"test.py", line one,inch<module>Mye (0) File"test.py", line7,inchMye raise Exception ("Invalid level!", Level) Exception: ('Invalid level!',0)
user-defined exceptions

By creating a new exception class, programs can name their own exceptions. Exceptions should be typical of inheriting from the exception class, either directly or indirectly.

The following is an example of a runtimeerror-related instance in which a class is created and the base class is runtimeerror, which is used to output more information when the exception is Triggered.

In the try statement block, after the user-defined exception executes the except block statement, the variable e is used to create an instance of the Networkerror class.

class networkerror (runtimeerror):    def __init__ (self, arg):        = arg

After you define the above class, you can trigger the exception as Follows:

Try :    Raise Networkerror ("badhostname") except Networkerror,e:    Print E.args

Python--exception handling--12

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.