Python Exception handling

Source: Internet
Author: User

Take a look at the code first:

Def calc (A, B):
res = A/b
return res

def main ():
Money = input (' Enter how much: ')
month = input (' Also several months: ')
res = calc (int (money), Int (month))
return res

Main ()

When you run the Money input 10,month enter 0 to see the results:

Run when money input Aa,month input HHH, view results: HHH

In the process of running, we need to process the exception, let the code continue to execute after the part, modify the code:

def main ():
Money = input (' Enter how much: ')
month = input (' Also several months: ')
Try
res = calc (int (money), Int (month))
Except Zerodivisionerror as E: #try里面的代码出错, go except
Print (' The number of months to repay cannot be 0 ', e)
Print (' should also%s '% res per month)

Run, Money input 10,month enter 0 to view the results:

The reason for the error is that the code in the try is wrong and the except,res does not have a value at all, so let's change the code again:

def main ():
Money = input (' Enter how much: ')
month = input (' Also several months: ')
Try
res = calc (int (money), Int (month))
Except Zerodivisionerror as E: #try里面的代码出错, go except
Print (' The number of months to repay cannot be 0 ', e)
Else
Print (' should also%s '% res per month)

When we enter a letter, we still get an error, we can continue to modify the code:

def main ():
Money = input (' Enter how much: ')
month = input (' Also several months: ')
Try
res = calc (int (money), Int (month))
Except Zerodivisionerror as E: #try里面的代码出错, go except
Print (' The number of months to repay cannot be less than 1 ', e)
Except ValueError as E: #继续捕获其他异常
Print (' input must be an integer. %s '%e)
Else
Print (' should also%s '%res per month)

There may be many unknown exceptions to the code, and we cannot predict that we can modify the code to catch all exceptions in order for the code to execute without terminating the error:

def main ():
Money = input (' Enter how much: ')
month = input (' Also several months: ')
Try
res = calc (int (money), Int (month))
Except Zerodivisionerror as E: #try里面的代码出错, go except
Print (' The number of months to repay cannot be less than 1 ', e)
Except ValueError as E: #继续捕获其他异常
Print (' input must be an integer. %s '%e)
Except Exception as E: #捕捉全部异常
Print (' Catch all exceptions%s '%e)
Else
Print (' should also%s '%res per month)

When we use try, we can also capture the complete error message, we need to introduce a new module Traceback, modify the code:

Import Traceback
def main ():
Money = input (' Enter how much: ')
month = input (' Also several months: ')
Try
res = calc (int (money), Int (month))
Except Zerodivisionerror as E: #try里面的代码出错, go except
Traceback.print_exc () #只是输出报错的详细信息, does not affect code run
Print (' The number of months to repay cannot be less than 1 ', e)
Except ValueError as E: #继续捕获其他异常
Print (' input must be an integer. %s '%e)
Except Exception as E: #捕捉全部异常
Print (' Catch all exceptions%s '%e)
Else
Print (' should also%s '%res per month)

Execution Result:

================================== I'm a split line ==================================================

Import Pymysql
Def main2 ():
Try
conn = Pymysql.connect (host= ' 122.932.122.11 ', user= ' root ', password= ' 123456 ', db= ' test ')
Except Exception as E:
Print (' database not connected,%s '%e)
Else
cur = conn.cursor ()
Except Exception as E:
Print (' SQL statement has errors! %s SQL is "%s"% (e, SQL))
Else
res = Cur.fetchall ()
return res
#except和else不会同时走到, you can only walk the same, so you need to put the close cursor and the connection in two branches
Finally: #不管有没有捕捉到异常, will come here
Cur.close ()
Conn.close ()

================================== I'm a split line ==================================================

Import requests
def req ():
r = Requests.get (' http://api.nnzhp.cn/api/user/all_stu ', headers={' Referer ': ' http://api.nnzhp.cn/'})
If Len (R.json () [' Stu_info ']) <0:
Pass
Else
Raise Exception (' Interface not data ') #主动抛出异常
Req ()

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.