Python Exception handling

Source: Internet
Author: User

First, exception handling

In the process of running the program, you will always encounter a variety of errors. Program An error stopped running, then we can not let the program stop running it, this time we need to catch the exception, by catching the exception, we do the corresponding processing.

Let's begin by writing a function that implements the division operation.

1234567891011 def Calc(a,b): return a/b Print(calc(5,1))#调用, no error, the result is 5.0 >>> 5.0 Print(calc(5,0))#再次调用, this time is wrong, because dividend cannot be 0, the following report a bunch of errors, the program stopped running >>> zerodivisionerror: Division by Zero

This time we need to catch the exception, if the divisor is 0, it prompts the user to pass in the wrong parameter, re-incoming.

Catching exceptions using try....except .... keyword, that is, you write code, the first to consider what the code might be wrong, and then do the corresponding processing, try inside is containing the code you do processing, except inside is out of some kind of error, I how to deal with, below we change code, catch exception.

12345678910111213 def Calc(a,b): try: res = a/b except zerodivisionerror as e:#如果是除数为0的错误, the return divisor cannot be 0, the as E represents the return of the wrong information to the E return ' divisor cannot be 0! ' return res#这个是如果没有这个异常的话, the result is returned Print(calc(5,0))#这样再调用就不会出来错误了, the return divisor cannot be 0.

Above is catching the exception, of course, the above can only catch the divisor of 0 error, if there are other errors can not be caught; there is a finally usage, that is, whether the exception is not out of the execution; Try also has a can catch all the exceptions, and else the use of it is not an exception when the time to do, The following code is used to explain.

123456789101112131415161718192021 def Calc(a, b): try: # catch Exception res = a / b except zerodivisionerror as e: return ' divisor cannot be 0! ' except keyerror as e: # Catch Keyerror This exception, of course, this piece of code is useless to the dictionary, So there will be no keyerror this error, I just give an example return ' keyerror error ' except Exception as e: # This is catching all the anomalies, no matter what anomalies you can capture Print(' other exceptions ') return e #返回错误信息 Else: #这个else和上面的try对应的, it's not unusual. Print(' no exception ') return res finally: #这个finally是不管这个段代码有没有出异常都走它 Print(' Haunt the anomalies all walk me here ') Print(calc(5, 0)) #出除数异常了, will return a divisor cannot be 0! and execute the code inside finally Print(calc(5, 1)) #这个没有出异常, go to the other thing, return the result, Executes the code in the finally Print(calc(5, ' s ')) #这个也走异常了, divisor is a string, certainly cannot be removed, Just take the code that catches all the exceptions and executes the code in the finally

Second, some common abnormal information:

1234567891011121314151617181920212223 Attributeerror: attempted to access a property that an object does not have, such as foo. X, but foo has no attribute x IOError: Input /Output exception, usually cannot open file Importerror: Unable to import module or package, usually path problem or name error Indentationerror: Code not aligned correctly, syntax errorindexerror: Subscript index is out of sequence bounds, e.g. x has only three elements, but tries to access x[3] Keyerror: Attempting to access a key that does not exist in the dictionarykeyboardinterrupt:Ctrl+c is pressed nameerror: Using a variable that has not been assigned to an objectsyntaxerror: syntax error TypeError: The Incoming object type does not match the requirements Unboundlocalerror: Attempts to access a local variable that is not yet set, typically because there is another variable with the same name outside of the code blockvalueerror: Pass in a value that is not expected by the caller, even if the value is of the correct type

Three, the initiative throws the exception

The initiative throws an exception, that is, we in the code to let it automatically throw an exception, and then capture, for example, when we write automated test script, the results and expectations do not meet, you can actively throw an exception information, and then catch, do other processing, actively throw the exception using the Raise keyword.

1234567 try:   raise keyerror#主动抛出一个keyerror的异常  except keyerror as e: Print(' This is the exception I'm actively throwing ')

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.