Python Exception handling detailed

Source: Internet
Author: User
Tags stack trace
This section focuses on the principles and main forms of exception handling in Python.


1. What is an exception


Python uses exception objects to represent exceptions. An exception is thrown when the program encounters an error during run time. If the exception object is not processed or captured, the program will backtrack to abort execution.


2. Throw an exception


Raise statement, raise followed by exception exception class or exception subclass, you can also add the exception information in the parentheses of exception.


>>>raise Exception (' message ')


Note: The exception class is the base class for all exception classes, and we can also create our own defined exception classes based on this class, as follows:


Class Somecustomexception (Exception): Pass


3. Catch exception (Try/except statement)


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.


Multiple exceptions can be thrown in a try statement block:

Try:     x = input (' Enter the first number: ')     y = input (' Enter the second number: ')     print x/y except Zerodivisio Nerror:     print "The second number can ' t be zero!" except TypeError:     print "which wasn ' t a number, was it?"


A except statement can catch multiple exceptions:

Try:     x = input (' Enter the first number: ')     y = input (' Enter the second number: ')     print x/y except (zerodivisi OnError, TypeError, nameerror):  #注意except语句后面的小括号     print ' Your numbers were bogus ... '

Access the caught exception object and print out the exception information:

Try:     x = input (' Enter the first number: ')     y = input (' Enter the second number: ')     print x/y except (zerodiv Isionerror, TypeError), E:     print E

Catch all exceptions to prevent unexpected anomalies from being missed:

Try:     x = input (' Enter the first number: ')     y = input (' Enter the second number: ')     print x/y except:     print ' someting wrong happened ... '


4, Else clause. In addition to using the EXCEPT clause, the ELSE clause can be used, and if no exception is thrown in the try block, the ELSE clause is executed.

While 1:     try:         x = input (' Enter the first number: ')         y = input (' Enter the second number: ')         value = x/y
  
   print ' x/y is ', value     except:         print ' Invalid input. Please try again. '     else: Break         
  


An ELSE clause is executed when the user enters the x and Y values legitimately after the code block is run, allowing the program to exit execution.

5, finally clause. Whether or not an exception occurs in a try clause, the finally clause is bound to be executed, or it can be used with the ELSE clause. The finally clause is commonly used at the end of a program to close a file or network socket.

Try:     1/0 except:     print ' unknow variable ' else:     print ' that went well ' finally:     print ' cleaning up '

6. Exceptions and functions

If an exception is thrown inside a function without being processed, it is passed to the function call, and if it is not processed, the exception is passed to the main program and terminated as a stack trace.

def faulty ():    raise Exception (' someting is wrong! ') Def ignore_exception ():    Faulty ()      def handle_exception ():    try:        faulty ()    except exception, E:        print ' Exception handled! ', e  handle_exception () ignore_exception ()

In the above code block, the function handle_exception () after calling faulty (), the faulty () function throws an exception and is passed to Handle_exception (), which is processed by the Try/except statement. The Ignare_exception () function does not have exception handling for faulty (), which throws an exception to the stack trace.

NOTE: Conditional statement If/esle can implement the same functionality as exception handling, but conditional statements may be less natural and readable.

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