Seventh Python exception handling

Source: Internet
Author: User

What is an exception?

As the name implies, the exception is that the program does not work properly for some reason, such as indentation errors, missing packages, environment errors, connection timeouts, and so on, all of which throw exceptions. A robust program should be able to anticipate anomalies should be handled accordingly, to deal with some simple anomalies, so that the better guarantee the program for a long time to Run. Even if there is a problem, the maintainer can see the problem at the same glance. So this section explains how to deal with exceptions and make your program more Robust.

7.1 Catching exception syntax

Try...except...try:expressionexcept [except Type]: Expression

7.2 Exception Types

Common Types of Exceptions:

Exception type

Use

SyntaxError Syntax error
Indentationerror Indentation Error
TypeError
Object type does not conform to requirements
Importerror Module or package import error, generic path or name error
Keyerror
A key that doesn't exist in the dictionary
Nameerror Variable does not exist
Indexerror Subscript out of sequence range
IOError Input/output exception, usually cannot open file
Attributeerror There are no attributes in the object
Keyboardinterrupt Keyboard accepted to CTRL + C
Exception Generic exception type; generally catches all exceptions

There are also some exception types that can be viewed through dir:

>>> import exceptions>>> dir (exceptions) [' arithmeticerror ',  ' Assertionerror ',  ' attributeerror ',  ' baseexception ',  "buffererror ',  ' BytesWarning ',  ' Deprecationwarning ',  ' eoferror ',  ' environmenterror ',  ' Exception ',,  ' Floatingpointerror ',   ' futurewarning ',  ' generatorexit ',  ' IOError ',  ' importerror ',  ' importwarning ',  ' Indentationerror ',  ' indexerror ',  ' keyerror ',  "keyboardinterrupt ',  ' LookupError ',  ' Memoryerror ',  ' nameerror ',  ' notimplementederror ',  "oserror ',  ' Overflowerror ',  ' Pendingdeprecationwarning ',  ' referenceerror ',  ' runtimeerror ',  ' runtimewarning ',  ' StandardError ',  ' stopiteration ',  ' syntaxerror ',  "syntaxwarning ',  ' SystemError ',  ' Systemexit ',  ' taberror ',  ' TypeError ',  "unboundlocalerror ',  ' Unicodedecodeerror ',  ' Unicodeencodeerror ',  ' Unicodeerror ',  ' UniCodetranslateerror ',  ' unicodewarning ',  ' userwarning ',  "valueerror ',  ' Warning ',  ' Zerodivisionerror ',  ' __doc__ ',  ' __name__ ',  ' __package__ ']

7.3 Exception Handling

For example, to print a variable that is not defined

>>> Print Atraceback (most recent call last): File "<stdin>", line 1, in <module>nameerror:name ' a ' is not defined

Throws an exception, indicating that the name is Undefined. If the program encounters this situation, it Terminates.

So we can do this, when the variable is not assigned to the variable, otherwise continue to Operate.

>>> try: Print a ... except nameerror: ... a = "" ...>>> a "

This avoids the occurrence of the Exception. In development, you often don't know what the exception type is, so you can use the exception type to catch all the exceptions:

For example, to print a property that is not in a class object

>>> Class A: ... a = 1 ... b = 2...>>> c = A () >>> try: ... print c.c ... Except Exception: ... print "Error ..." ... Error ...

Sometimes also want to print out the abnormal information, how to do it?

You can save the error output to a variable, according to the example above:

>>> try: Print c.c ... Except Exception, e: ... print "Error:" + str (e) ... ERROR:A instance has no attribute ' C ' # You can also use the AS keyword to save the error output to a variable >>> try: ... print c.c ... Except Exception as E: ... print "Error:" + str (e) ... ERROR:A instance has no attribute ' C '

When there are several possibilities for the type of exception that occurs, you can write multiple except:

>>> try: Print a ... except nameerror, e: ... print "nameerror:" + str (e) ... except keyerror, e: ... print "keyerror:" + str (e) ... Nameerror:name ' A ' is not defined

Note: except can also not specify the exception type, then ignores all exception classes, which is risky, it also captures Ctrl + c, sys.exit, and so On. So it's better to use except Exception.

7.4 Else and finally statements

7.4.1 Else Statement

Indicates that if the code in the try does not throw an exception, then else is Executed.

Continue to follow the examples of the classes defined Above:

>>> try: print c.a ... except Exception as e: ... else: .... print "else".    .."    ... 1 Else ...

7.4.2 Finally statement

Indicates that a finally is performed whether or not an exception occurs.

>>> try: print c.c ... except Exception as e: .... print e ... finally: ... print "fi    Nally ... "... A instance has no attribute ' C ' finally ...

Generally used for cleanup work, such as opening a file, regardless of whether the file is successful, should close the File.

7.4.3 try...except...else...finally

This is a complete statement that, when used together, makes exception handling more Flexible.

    #!/usr/bin/python         # -*- coding: utf-8 -*-    try:         print a    except exception as e:         print  "error: "  + str (e)      else:        print  "else ..."     finally :         print  "finally ..."              # python test.py    python  test.py    error: name  ' A '  is not defined     Finally ... 

It is important to note that the order of their statements must be try...except...else...finally, otherwise the syntax is wrong! Inside else and finally are optional.

7.5 Custom Exception Classes

The raise statement is used to manually throw an exception using the Method:

Raise Excepttype (exceptinfo)

For example, throw a specified exception

>>> raise Nameerror (' test except ... ') Traceback (most recent call last): File "<stdin>", line 1, in <mod Ule>nameerror:test except ...

The raise parameter must be an instance of an exception or a exception subclass.

The above used exception subclass, then I define an instance of an exception, need to inherit the exception class:

>>> class Myerror (Exception): ... def __init__ (self, value): ... self.value = value ... def __str__ (self):.      .. Return self.value...>>> raise Myerror ("myerror ...") Traceback (most Recent call last): File "<stdin>", Lin E 1, in <module>__main__. Myerror:myerror ...

7.6 Assert statement

The Assert statement is used to check whether the conditional expression is true and not true to trigger an Exception. Also called an assertion Statement.

Generally used when a condition is true to work properly.

>>> assert 1==1>>> assert 1!=1traceback (most recent call last): File "<stdin>", line 1, in <m Odule>assertionerror>>> assert range (4) ==[0,1,2] Traceback (most Recent call last): File "<stdin>", Li Ne 1, in <module>assertionerror# Add exception description information >>> assert 1!=1, "assert description ..." Traceback (most recent CA ll last): File ' <stdin> ', line 1, in <module>assertionerror:assert description ...


This article is from the "Li Zhenliang technology blog" blog, Make sure to keep this source http://lizhenliang.blog.51cto.com/7876557/1861147

Seventh Python exception handling

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.