上一篇: With關鍵字的使用 | 手把手教你入門Python之七十八 下一篇: 詳解疊代器的使用 | 手把手教你入門Python之八十 本文來自于千鋒教育在阿裡雲開發者社群學習中心上線課程 《Python入門2020最新大課》 ,主講人姜偉。
自定義異常
系統内置的異常:
# ZeroDivisionError
print(1 / 0)
# FileNotFoundError
open('xxx.txt')
# FileExistsError
import os
os.mkdir('test') # 多次建立同名的檔案夾
# ValueError
int('hello')
# KeyError
person = {'name':'zhangsan'}
person['age']
# SyntaxError
print('hello','good')
# IndexError
name = ['zhangsan', 'lisi']
names[5]
要求:讓使用者輸入使用者名和密碼,如果使用者名和密碼的長度在6~12位正确,否則不正确。
class LengthError(Exception):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '長度必須要在{}至{}之間'.format(self.x, self.y)
password = input('請輸入您的密碼:')
m = 6
n = 12
if m <= len(password) <= n:
print('密碼正确')
else:
# print('密碼格式不正确')
# 使用 raise 關鍵字可以抛出一個異常
raise LengthError(m, n)
# 把密碼儲存到資料庫裡
print('将密碼儲存到資料庫')
你可以⽤raise語句來引發⼀個異常。異常/錯誤對象必須有⼀個名字,且它們應是Error或Exception類的⼦類下⾯是⼀個引發異常的例⼦:
class ShortInputException(Exception):
'''⾃定義的異常類'''
def __init__(self, length, atleast):
#super().__init__()
self.length = length
self.atleast = atleast
def __str__(self):
return '輸⼊的⻓度是 %d,⻓度⾄少應是 %d'% (self.length, self.atleast))
def main():
try:
s = input('請輸⼊ --> ')
if len(s) < 3:
# raise 引發⼀個⾃定義的異常
raise ShortInputException(len(s), 3)
except ShortInputException as result: # x這個變量被綁定到了錯誤的執行個體
print('ShortInputException:' % result)
else:
print('沒有異常發⽣.')
main()
運⾏結果如下:
