异常代码的处理格式
try:
尝试执行的代码
except:
出现错误的处理
示例代码:解决数字输入时的错误
try:
num = int(input('请输入一个数字'))
except:
print('请输入正确的整数')
多个异常的处理方式
"""
整数,8除
"""
try:
num = int(input())
print(8/num)
except ValueError:
print('wrong input')
except ZeroDivisionError:
print('0 wrong')
except Exception as r:
print('unknown')
finally:
print('**************')
主动抛出异常
def inputpasswd():
pwd = input('Input your password:')
if len(pwd) >= 8:
return pwd
print('主动抛出异常')
ex = Exception('密码长度不足')
raise ex
try:
print(inputpasswd())
except Exception as r:
print(r)