异常
开发中,可能出现各种异常,这里不做列举,遇到了就捕获就好。
语法:
try:
pass
except [ExceptionName [as alias]]:
pass
捕获异常
# 作者:咸瑜
# 代码时间:2022年12月1日
a = 1
b = 0
try:
print(a / b)
except ZeroDivisionError: # 如果不加上指定捕获的异常 那么捕获全部异常
print("除数不能为0")
# ------------------------------------------------------------------------------------
a = input("请输入A:")
b = input("请输入B:")
try:
print(int(a) / int(b))
except BaseException: # BaseException 是 Exception 的父类,作为子类的Exception无法截获父类BaseException类型的错误
print("除数不能为0")
else:
print("Result:", (int(a) / int(b)))
# ------------------------------------------------------------------------
a = input("请输入A:")
b = input("请输入B:")
try:
print(int(a) / int(b))
except BaseException as e: # BaseException 是 Exception 的父类,作为子类的Exception无法截获父类BaseException类型的错误
print("出错了")
print("错误是:", e)
else:
print("Result:", (int(a) / int(b)))
finally:
print("不管你错不错,你都要执行我")
# 请输入A:1
# 请输入B:0
# 出错了
# 错误是: division by zero
# 不管你错不错,你都要执行我
模块打印异常
import traceback
a = input("请输入A:")
b = input("请输入B:")
try:
print(int(a) / int(b))
except:
print("出错了")
traceback.print_exc()
# 请输入A:1
# 请输入B:0
# 出错了
# Traceback (most recent call last):
# File "C:\Users\Bi-Hu\PycharmProjects\pythonProject\s1.py", line 21, in <module>
# print(int(a) / int(b))
# ZeroDivisionError: division by zero
标签:Python11,except,int,print,input,异常,输入,BaseException
From: https://www.cnblogs.com/bi-hu/p/16941805.html