在程序開發時,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的異常處理語句.
try:
可能出現錯誤的代碼塊
except:
出現錯誤後執行的代碼塊
else:
A block of code that executes without exception
finally:
The block of code where the exception occurs or not
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
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
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