Introduction to Python Exceptions

Source: Internet
Author: User
Tags integer division python script

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.

Syntax :

以下为简单的try....except...else的语法:try:<语句>        #运行别的代码except <名字>:<语句>        #如果在try部份引发了‘name‘异常except <名字>,<数据>:<语句>        #如果引发了‘name‘异常,获得附加的数据else:<语句>        #如果没有异常发生

Working principle
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

Example:

#coding=utf-8try :    fp = open("c:\\file.txt", ‘r‘)    fp.write("test")    fp.close()except IOError :    print u"文件写入失败!"else :    print u"文件写入成功!"


Nested try

while True:    try:        try:            number = int(raw_input("input the number: "))        except:            print "try again."            1/0#此处的异常被抛给上层的try    except Exception,e:        print e    else:        break

The above code executes the procedure:
First execute inner try, if trigger exception, catch inner exception, print message "Try Again"
Then execute code 1/0, throw an exception, this exception is thrown to the upper try, and then by the upper try corresponding to the except capture and print the exception information, if no exception occurred, jump out of the loop

Except with no exception type

try:    1/0except:    print "error occur."else:print "no error occur"

Except with multiple exception types
Mode 1:except followed by multiple exceptions, with parentheses

try:    fp =open ("e:\\34.txt")    aexcept (IOError,NameError):    print "error occur.":else:print "no error occur"

Mode 2: Multiple except are followed by a corresponding exception, and the first exception that occurs in a try is captured

try:    fp = open("e:\\34.txt")    aexcept IOError:    print "IOError occur."except NameError:    print "NameError occur."else:    print "no error occur"

Try-finally/else statements
Finally, the statement will always be executed, whether or not an exception occurred
Finally needs to be put behind else.

import systry:    s = raw_input(‘Enter something --> ‘)except KeyboardInterrupt:    print ‘\nWhy did you do an Ctrl+c on me?‘ #ctrl+c    sys.exit() # exit the programexcept:    print ‘\nSome error/exception occurred.‘ #ctrl+z 报错else:    print "no exception occur!"finally:    print "finally is executed!"

Try-finally

#coding=utf-8try:    fh = open("c:\testfile", "r")    try:        content = fh.read()        print content    finally:        print u"关闭文件"        fh.close()except IOError:print u"Error: 没有找到文件或读取文件失败"

The execution result of the file does not exist:


Execution result of File existence

Except carrying exception parameters
An exception can take a parameter that can be used as the output exception information parameter. Use the except statement to capture the different
Constant parameters

try :    fp = open("c:\\fileTest11.txt", ‘r‘)    try :        content = fp.read()    finally :        print u"关闭文件!"        fp.close()except Exception, e :    print u"文件读取失败!"    print u"打印异常信息:" print e

The file does not exist with the result of execution:

Triggering an exception
Python uses the keyword raise to trigger an exception yourself.
The syntax format is as follows:
raise[someexcpetion[, args [, Traceback]]
The someexcpetion in the statement is an exception type, such as nameerror, optional; parameter
Args is an exception parameter value, usually a tuple, optional if not supplied as "None". At last
One parameter is also optional, which is rarely used, and if present, is the tracking exception object. If there is
Other parameters (arg or traceback), you must provide a someexcpetion

def exceptionTest(num):    if num < 0:        raise Exception("Invalid num")#也可以是 raise Exception,”invalid num”    else:        print num    if num == 0:        raise ZeroDivisionError("integer division or modulo by zero")#调用函数,触发异常exceptionTest(-12)

Execution Result:


Custom Exceptions:

By creating a new Exception class, programs can create their own specific exceptions. Custom exceptions are required
To inherit the exception base class (Exception Class), it is also possible to inherit specific exception classes (such as
RuntimeError), by direct or indirect means.

#coding=utf-8class Networkerror(RuntimeError):    # 重写默认的__init__()方法,抛出特定的异常信息    def __init__(self, value):        self.value = value#触发自定义的异常try:    raise Networkerror("Bad hostname")except Networkerror, e:    print "My exception occurred, value:", e.value执行结果:

Exception throwing mechanism:
1. If an exception occurs at run time, the interpreter will find the appropriate processing statement (called handler).
2, if not found in the current function, it will pass the exception to the upper call function, see
Can you handle it there?
3. If the outermost (global "main") is not found, the interpreter will exit and print
Traceback to let the user find out why the error occurred.
Attention:
While most errors cause exceptions, an exception does not necessarily represent an error, and sometimes they are just a
Warning, sometimes they may be a terminating signal, such as exiting a loop.

Python Standard Exceptions:

Exception Name Description

Baseexception base class for all exceptions
Systemexit Interpreter Request Exit
Keyboardinterrupt user interrupt execution (usually input ^c)
Exception base class for general errors
Stopiteration iterator with no more values
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 has no built-in input to reach the EOF tag
EnvironmentError base class for operating system errors
IOError Input/output operation failed
OSError Operating system error
Windowserror system call failed
Importerror Import Module/object failed
Lookuperror base class for invalid data queries
This index is not in the Indexerror sequence (index)
This key is not in the Keyerror map
Memoryerror Memory overflow error (not fatal for Python interpreter)
Nameerror object not declared/initialized (no attributes)
Unboundlocalerror access to uninitialized local variables
Referenceerror Weak reference (Weak reference) attempts to access objects that have been garbage collected
RuntimeError General run-time errors
Notimplementederror methods that have not yet been implemented
SyntaxError Python Syntax error
Indentationerror Indent Error
Taberror Tab and Space mix
Systemerror General Interpreter System error
TypeError operations that are not valid for types
ValueError invalid arguments passed in
Unicodeerror Unicode-related errors
Unicodedecodeerror Unicode decoding Error
Unicodeencodeerror Unicode Encoding Error
Unicodetranslateerror Unicode Conversion Error
Base class for Warning warnings
Deprecationwarning warning 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 runtime behavior (runtime behavior)
Syntaxwarning warning of suspicious syntax
Userwarning warning for user code generation

The standard exception set listed above, all exceptions are built-in. So they are either before the script is started or in mutual
When the command line prompt appears, it is already available.
All standard/built-in exceptions are derived from the root exception. Currently, there are 3 direct from baseexception
Derived exception subclasses: Systemexit,keyboardinterrupt and exception. All the others.
The built-in exceptions are exception subclasses.
Python2.5 start, all of the exceptions are baseexception subclasses.

Introduction to Python Exceptions

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.