程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Exceptions and handling -- python

編輯:Python

1. 異常處理語句

在程序開發時,Some errors do not appear on every run,例如,password entry problem,At this time, it is necessary to handle the exceptions that may occur in the program,內部消化,讓程序繼續運行,下面來學習python的異常處理語句.

1.1 語法格式

try:
可能出現錯誤的代碼塊
except:
出現錯誤後執行的代碼塊
else:
A block of code that executes without exception
finally:
The block of code where the exception occurs or not

1.2 捕獲異常

1.1.2 捕獲所有異常

exceptThe specific exception name that was caught is not followed,表示捕獲所有異常

while True:
try:
a = int(input('數字a: '))
b = int(input('數字b: '))
result = a / b
# print('result為: ', result)
except:
print('程序出錯')
else:
print('result為: ', result)
finally:
choice = input('Enter the number of your choice: 1繼續,2退出: ')
if choice == '1':
continue
else:
break

1.2.2 Output the specific exception name that was caught

while True:
try:
a = int(input('數字a: '))
b = int(input('數字b: '))
result = a / b
# print('result為: ', result)
except Exception as err:
print('程序出錯: %s'% err)
else:
print('result為: ', result)
finally:
choice = input('Enter the number of your choice: 1繼續,2退出: ')
if choice == '1':
continue
else:
break

1.2.3 Handle specific exceptions

while True:
try:
a = int(input('數字a: '))
b = int(input('數字b: '))
result = a / b
# print('result為: ', result)
except ZeroDivisionError:
print('注意!!數字b不能為0!')
except ValueError:
print('注意!! Input must be a decimal number!')
except Exception as err:
print('程序出錯: %s'% err)
else:
print('result為: ', result)
finally:
choice = input('Enter the number of your choice: 1繼續,2退出: ')
if choice == '1':
continue
else:
break


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved