"Python" Exception handling

Source: Internet
Author: User

1. Throwing Exceptions and custom exceptions

Python uses an Exception object (Exception object) to represent an exception, and an exception is thrown when an error is encountered. If the exception object is not handled or captured, the program terminates execution with the so-called backtracking (Traceback, an error message).

1.1 Raise statements

The Raise keyword in Python is used to throw an exception, basically the same as the throw keyword in C # and Java, as follows:

#-- Coding:utf-8-def Thorwerr ():Raise Exception (" throws an exception ")# Exception : Throws an exception 7 thorwerr ()          

raiseAfter the keyword is thrown is a generic exception type (Exception), in general, the more the exception throws the more detailed the better, Python exceptions built a lot of exception types in the module, by using dir the function to see exceptions the type of the exception, as follows:

Import Exceptions# [' Arithmeticerror ', ' assertionerror ' ...] Print dir (exceptions)   

Passing exceptions

Catching an exception, but trying to re-throw it (passing an exception), you can use a statement without arguments raise :

1#--Coding:utf-8--2ClassMuffledcalculator:3 muffled =False4Def Calc (self,expr):  5 try : 6 return eval (expr)  7 except 8 if  Self.muffled: 9 print Span style= "color: #800000;" > ' 

1.2 Custom Exception Types

Python can also customize its own special type of exception, only to inherit from the exception class (directly or indirectly):

Class Somecustomexception (Exception):    pass 

2. Catching exceptions

Like in C # try/catch , Python uses try/except keywords to catch exceptions, as follows:

#-- Coding:utf-8-try:    print 2/0except' divisor cannot be 0'    

2.1 Catching multiple exceptions

In a except statement, only the exception type that is declared later is caught, and if it is possible to throw another type of exception, you need to add a except statement, or you can specify a more general exception type such as: Exception , as follows:

#-- Coding:utf-8-try:    Print 2/' 0 'except' divisor cannot be 0'except ' Other types of exceptions '              

To catch multiple exceptions, in addition to declaring multiple except statements, you can also list multiple exceptions as tuples after a single except statement:

#-- Coding:utf-8-try:    Print 2/' 0 'except' An exception occurred '  

2.2 Getting exception information

Each exception will have some exception information, in general we should record these exception information:

#-- Coding:utf-8-try:    Print 2/'0'except#     

3. Finally clause

finallyClauses and try clauses are used together, but unlike except statements finally , try finally the code within the clause is executed regardless of whether an exception occurs inside the clause. In general, they are finally often used to close files or in sockets.

#-- Coding:utf-8-try:    Print 2/' 0 'except' An exception occurred '  Finally' execute ' whether or not an exception occurs            

Common Python exception types

"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.