資安

自定義異常

本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《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()

運⾏結果如下:
image.png

配套視頻

Leave a Reply

Your email address will not be published. Required fields are marked *