Python Exception Handling Summary

Source: Internet
Author: User
This article is a detailed list of Python common exception handling, for your reference, as follows:

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

①.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 ("Throw an Exception") # Exception: Throws an exception Thorwerr ()

After the Raise keyword is thrown is a generic exception type (Exception), in general, the more the exception throws the more detailed the better, Python built a lot of exception types within the exceptions module, by using the Dir function to see the type of exception in exceptions, 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 the Raise statement without parameters:

#--Coding:utf-8--class muffledcalculator:  muffled = False  def calc (self,expr):    try:      return eval ( Expr)    except Zerodivisionerror:      if self.muffled:        print ' Division by zero is illegal '      else:        raise

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

Similar to Try/catch in C #, Python uses the try/except keyword to catch an exception, as follows:

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

①. Capturing 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 Zerodivisionerror:  print ' divisor cannot be 0 ' except Exception:  print ' 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 (zerodivisionerror,exception):  print ' An exception has occurred '

②. 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 (zerodivisionerror,exception) as E:  # Unsupported operand type (s) for /: ' int ' and ' str '  print E

3. Finally clause

The finally clause is used in conjunction with a try clause but unlike the except statement, finally executes the code within the FINALLY clause regardless of whether an exception occurs inside the TRY clause. In general, finally, it is often used to close a file or in a socket.

#--Coding:utf-8--try:  print 2/' 0 ' except (zerodivisionerror,exception):  print ' has an exception ' finally:  print ' Regardless of whether an exception occurred, execute '
  • 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.