Python Error handling try...except...finally ... Error handling mechanism.

Source: Internet
Author: User
Tags integer division

Learned about Python's error handling today.

In the process of program processing, there are often errors, once the error is very troublesome. So some high-level languages are usually built into a set of try...exept...finaly ... Error-handling mechanism, Python is no exception.

Here's an example of a try:

 try:print (10/0 print (except zerodivisionerror as e:print ( ' except: ', E) finally:print ( finally ... ') print (             
Because 10/0 is wrong, this time the try this part will execute the error, then the subsequent code will not execute, will jump directly to the error handling code, that is, the except statement block, after execution if there is a finally statement block to run finally, this concludes.

try...except: division by zerofinally...END
由此可以看出r = 10/0后面的print(‘result:‘,r)没有运行,反而except捕捉到了错误所以输出
division by zero
Finally, the finally is executed.


If you change the "R = 10/0 '" of the program above to "R = 10/5"
The output will be:
try...result: 2finally...END
可以看出except没有被执行,但是finally是被执行了。



如果一段程序有多种语句上的错误,我们可以用不同的except语句处理。我们可以用多个except捕获程序里的多种错误。
例:
 try:print (10/int ( ' a ') print (except valueerror as e:print ( ' ValueError: ', e) except zerodivisionerror as e:print (finally:print ( Int () The function may execute valueerror, so the first except will catch the wrong value, the other except capture the zerodivisionerror, and if there is no error we can 
add an else in the back, and no error will execute the ELSE statement.
Example:
try:print (10/int ( ' 2 ') print (except valueerror as e:print ( ' ValueError: ', e) except zerodivisionerror as e:print (else:print ( ' no error! ') finally:              print(‘finally...‘)print(‘END‘)


python error is also class, all the error types inherit from Baseexception, there may be inheritance between the various types of errors, For example, Unicodeerror is a valueerror subclass,
如果catch语句中同时出现了这两个错误,且UnicodeError在ValueError的后面处理的,那么永远都捕获不到UnicodeError。


python中内置的常用错误类型继承关系:


使用try…excetp捕获错误一个好处是,可以跨层调用,比如main()调用foo(),foo()调用bar(),而错误是在bar中出现的,最后我们只需要在main()中捕获就行。


Deffoo (s): return 10/int (s) Span class= "function" >def bar (s): return foo (s) * 2def main (): try:bar ( ' 0 ') except Exception as e:print ( Finally:print ( 
that is, there is no need to catch errors at each error, Just catch the error at the right level. In this way, it greatly reduces the write try...except...finally ... of trouble.

call stack

If the error is not captured, he throws it up, preferably caught by the Python interpreter, prints an error message, and the program exits. See err.py:

/span>
 # err.py:< span class= "keyword" >def foo (s): return 10/int (s) def bar (s): return foo (s) * 2def Span class= "title" >main (): Bar ( ' 0 ') main ()      
 < span class= "keyword" >< Span class= "params" >< Span class= "title" >  execution results are as follows: 
/span>
$ python3 err.pyTraceback (most recent call last): File "err.py", line 11, in <module> main() File "err.py", line 9, in main bar(‘0‘) File "err.py", line 6, in bar return foo(s) * 2 File "err.py", line 3, in foo return 10 / int(s)ZeroDivisionError: division by zero

It 's not scary to make an error. Interpreting information is the key to locating errors. We can see the entire wrong call function chain from the top down:
error message First line:
call last):

Tell us that this is the wrong tracking information.
Line 2nd to 3rd:
  <module>    main()
The call to main () is wrong, and the 11th line of code in the code file err.py, but the reason is line 9th:
  File "err.py", line 9, in main bar(‘0‘)
The call to bar (0) went wrong, the 9th line of code in the code file err.py, but the reason is line 6th :
File "err.py", line 6, in bar return foo(s) * 2
 < span class= "keyword" >< Span class= "params" >< Span class= "title" >         
  file  "err.py" , line 3, in foo return 10/ Int (s)         
 < Span class= "params" >< Span class= "title" >           
ZeroDivisionError: integer division or modulo by zero

根据错误类型zerodivisionerror,我们判断,int(s)本身并没有出错,但是int(s)返回0,在计算10/0时出错,至此,找到错源头。








 
 




Python Error handling try...except...finally ... Error handling mechanism.

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.