# 第一种情况try:
num =input('please enter an integer number:')
num =int(num)print(num)except:print('please enter an right integer number!')#print('the rest of code that follows can continue execute!')# 第二种情况try:
num =input('please enter an integer number:')
num =int(num)print(num)except ValueError:print('an anomaly has occurred , please enter an right number!')# 第二种情况举例,当分母为 0 时报错,运行终止,只有错误符合数值类型错误类型才会向下执行try:
num =input('please enter an integer number:')
num =int(num)print(num)
a =10/ num
print(f'a: {a}')except ValueError:print('an anomaly has occurred , please enter an right number!')
运行结果:
# 第一种情况运行结果
please enter an integer number:jg # 输入的是字符,而不是整数
please enter an right integer number!
the rest of code that follows can continue execute!
# 第二种情况(指定异常)运行结果
please enter an integer number:kd # 输入字符类型
an anomaly has occurred , please enter an right number!
# 第二种情况举例,当分母为0时报错,运行终止,只有错误符合数值错误类型才会向下执行
please enter an integer number:0# 分母为0,不属于型错误(ZeroDivisionError),因此报错0
Traceback (most recent call last):
File "C:\Users\fighting!\Desktop\py_leaning\异常\py_异常捕获的基本语法.py", line 14,in<module>
a =10/ num
~~~^~~~~
ZeroDivisionError: division by zero
注意: ZeroDivisionError 不属于 ValueError指定类型错误
try:
num =input('please enter an integer number:')
num =int(num)print(num)
a =10/ num
print(f'a: {a}')except ValueError:print('an anomaly has occurred , please enter an right number!')except ZeroDivisionError:print('除数不能为0!')
try:
num =input('please enter an integer number:')
num =int(num)print(num)
a =10/ num
except Exception as e:print(f'错误信息为{e},请输入正确数字!')# 发生异常执行else:print(f'a: {a}')# 没有发生异常执行finally:print('The end!')# 不管有没有异常都执行
运行结果
please enter an integer number:1010
a:1.0
The end!
please enter an integer number:abc
错误信息为invalid literal forint()with base 10:'abc',请输入正确数字!
The end!
please enter an integer number:00
错误信息为division by zero,请输入正确数字!
The end!