杨桃的Python基础教程——第7章:Python函数(三)程序错误处理机制

本人CSDN博客专栏:https://blog.csdn.net/yty_7
Github地址:https://github.com/yot777/Python-Primary-Learning

7.5 程序错误处理机制

Python程序运行的过程中,如果发生了错误,程序会中断执行并抛出错误。如果程序员想在程序中自己捕获错误并加以处理,可以使用try...except...finally...的错误处理机制。

try来运行代码时,如果执行出错,则后续代码不会继续执行,而是直接跳转至错误处理代码,即except语句块。

执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕。

如果执行不出错,也要执行finally语句块。注意: finally语句也可以没有

Python使用try举例1:

try:
  print('try...')
  s=int(input('Please input number:'))
  print('Result:',10/s)
except ValueError as e1:
  print('ValueError Exception:', e1)
except ZeroDivisionError as e2:
  print('ZeroDivisionError Exception:', e2)
finally:
  print('END')

运行结果:
try...
Please input number:5
Result: 2.0
END

try...
Please input number:0
ZeroDivisionError Exception: division by zero
END

try...
Please input number:a
ValueError Exception: invalid literal for int() with base 10: 'a'
END

Python所有的错误都是从BaseException类派生的。如果搞不清楚会抛出什么名称的错误时,直接使用except Exception as e就可以了。

此外,如果没有错误发生,可以在except语句块后面加一个else,当没有错误发生时,会自动执行else语句。但如果程序有错误发生,就不执行else语句了。

Python使用try举例2:

try:
  print('try...')
  s=int(input('Please input number:'))
  print('Result:',10/s)
except Exception as e:
  print('Exception is:', e)
else:
  print('No error!')
finally:
  print('END')

运行结果:
try...
Please input number:5
Result: 2.0
No error!
END


try...
Please input number:0
Exception is: division by zero
END

try...
Please input number:a
Exception is: invalid literal for int() with base 10: 'a'
END

Python还可以利用raise语句自定义错误。

Python使用raise举例

def func1():
  s=int(input('Please input number:'))
  if s==0:
    raise Exception('除数不能为0!')
  print('Result:',10/s)
try:
  func1()
except Exception as err:
  print('错误信息是:',err)
else:
  print('No error!')

运行结果:
Please input number:2
Result: 5.0
No error!

Please input number:0
错误信息是: 除数不能为0!

Please input number:3.4
错误信息是: invalid literal for int() with base 10: '3.4'

Please input number:a
错误信息是: invalid literal for int() with base 10: 'a‘

(如果raise没有自定义的错误,Exception将返回Python定义的错误)

参考教程:

廖雪峰的Python教程

https://www.liaoxuefeng.com/wiki/1016959663602400

廖雪峰的Java教程

https://www.liaoxuefeng.com/wiki/1252599548343744

Python3 教程 | 菜鸟教程
https://www.runoob.com/python3/
 

如果您觉得本篇本章对您有所帮助,欢迎关注、评论、点赞!Github欢迎您的Follow、Star!
 

发布了25 篇原创文章 · 获赞 3 · 访问量 2159

猜你喜欢

转载自blog.csdn.net/yty_7/article/details/104187671
今日推荐