Python Exception handling

Source: Internet
Author: User

Exception handling is a functional module that is required for advanced programming languages.

First, the abnormal basis

In the programming process in order to increase the friendliness, fault tolerance and robustness, in the event of a bug in the program is generally not to display the error message to the user, but the reality of a hint of the page, popular is not to let users see the big Yellow Pages!!! Also, sometimes we do not want a small bug to the appearance of the whole program will crash, automatic exit or blue screen, we need to crawl this error exception, and processing, so that users can continue to use.

Try:    passexcept Exception as ex:    Pass

  Note: In Python3, except Exception, ex's alias method is no longer available, the comma is considered to be the delimiter of two exceptions, not the alias.

Here is an example:

While True:    num1 = input (' NUM1: ')    num2 = input (' num2: ')    try:        num1 = Int (NUM1)        num2 = Int (num2)        result = Num1 + num2    except Exception as ex:        print (' exception appears, information is as follows: ')        print (ex) run: NUM1:ASDNUM2:ASD exception occurred, The information is as follows: invalid literal for int. () with base: ' ASD ' NUM1:

Because there is no input int conversion of numeric characters, the system pops up, but we intercepted, printed the information we automatically and the original system information.

ii. types of anomalies

There are so many exceptions in Python that each exception is dedicated to handling an exception!!!

The following are some common exceptions:

Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input/output exception; it is basically impossible to open the file Importerror the module or package cannot be introduced is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access the X[5]keyerror Attempting to access a key that does not exist in the dictionary Keyboardinterrupt CTRL + C is pressed Nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot compile (personally think this is a syntax error, Wrong) TypeError the incoming object type is not compliant with the requirements Unboundlocalerror attempts to access a local variable that is not yet set, basically because another global variable with the same name causes you to think that you are accessing it valueerror a value that the caller does not expect , even if the type of the value is correct

More exceptions are here:

Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror more exceptions
View Code

If the exception that occurs in the program is not the one you set, you will still get an error.

# uncaught exception, program direct error S1 = ' Hello ' try:    int (s1) except Indexerror as ex:    print (ex)

In this example, you only set the capture Indexerror, and a valueerror will actually occur, so it will still get an error.

How do I write to capture multiple exceptions at once?

One is:

S1 = "Hello" try:    int (s1) except Indexerror as ex:    print (ex) except ValueError as ex:    print (ex) except Keyerror As ex:    print (ex)

The second is:

S1 = "Hello" try:    int (s1) except (Indexerror, ValueError, Keyerror) as ex:    print (ex)

The program is caught in the order of the exception, any one is caught, the exception is handled, and the code after the try and other exception handling code is ignored.

Universal Exception: Exception

In Python's exception, there is a universal exception: Exception, he can catch any exception, the equivalent of a person to all the work of the whole. Then you may have to ask, since there is this universal exception, other anomalies are not necessary!

Of course not, exceptions for special handling or reminders need to be defined first to accurately determine the type of error, store the error log, and finally define exception to ensure that the program runs correctly.

S1 = ' Hello ' try:    int (s1) except Keyerror,e:    print (' key error ') except Indexerror as E:    print (' index error ') except Exception as E:    print (' ERROR ')
Third, the complete structure of the anomaly
Try:    # main code block    passexcept Keyerror as E:    # exception when executing the block    passelse:    # The main block executes and executes the block    if no exception occurs Passfinally:    # Regardless of whether the exception occurred or not, the block pass will eventually be executed    

And the while loop may end up with an else statement. The syntax of try and except finally has else, and even finally. They provide more powerful logic processing power. They are optional and non-essential!

Iv. proactive triggering of anomalies

Python has built-in a key raise to proactively trigger exceptions.

Try:    raise ValueError (' An error has occurred! ') except ValueError as ex:    print (ex)

We often need it for debugging, interruption, and other situations.

Five, custom exceptions

The exception is also a class, just like a custom class, and of course you can customize the exception as long as it inherits the exception class.

Class Myexcept (Exception):    def __init__ (self, msg):        self.message = msg    def __str__ (self):        return Self.messagetry:    Raise Myexcept (' my exception! ') Except Myexcept as ex:    print (ex)
Vi. assertions

Python has a built-in assert keyword that represents assertions. It will judge the expression behind it, if true, then nothing happens, the program goes down, and if False, the exception pops up.

# assert Condition Assert 1 = = 1 assert 1 = = 2

  

  

Python Exception handling

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.