python怎么抛出异常不乱码
当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。
基础异常处理
try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。
如果你不想在异常发生时结束你的程序,只需在try里捕获它。
try的工作原理是,当开始一个try语句后,python就在当前程序的上下文中作标记,这样当异常出现时就可以回到这里,try子句(与try同级的except等)先执行,接下来会发生什么依赖于执行时是否出现异常。
如果当try后的语句执行时发生异常,python就跳回到try并执行第一个匹配该异常的except子句,异常处理完毕,控制流就通过整个try语句(除非在处理异常时又引发新的异常)。
如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印缺省的出错信息)。
如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句。
不管在try有无异常抛出时都会执行本级try对应的finally。
基础语法
try:
检测异常代码段except:
发生异常后执行代码段else:
未发生异常执行代码段finally:
最终执行代码段
例如
print("test1")
try:
s=input()
ifsisNone:
print("s是空对象")
print(len(s))#这句抛出异常
exceptTypeError:
print("类型错误空对象没有长度")
else:
print("noproblem")
finally:
print('endtest1')
以上内容为大家介绍了python怎么抛出异常不乱码,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
为什么Python爬虫使用MongoDB?
想必大家都知道,在从事网络爬虫工作之前,我们需要掌握很多知识,除了基本的爬虫原理之外,我们还需要学习框架、数据库等,其中就包含MongoDB...详情>>
2023-11-07 23:02:10
python如何进行类型转换的
python提供了将变量或值从一种类型转换成另一种类型的内置函数。1、int:将符合数学格式数字型字符串转换成整数。>>>int('123')1232、s...详情>>
2023-11-07 18:51:20
python怎么生成随机数
以下实例演示了python如何生成一个随机数:#生成0~9之间的随机数#导入random(随机数)模块importrandomprint(random.randint(0,9))执行以上代码...详情>>
2023-11-07 17:09:17
python如何删除空格
python中的字符串方法提供了如下常用的方法来删除空白:strip():删除字符串前后的空白。lstrip():删除字符串前面(左边)的空白。rstrip():删...详情>>
2023-11-07 14:57:44热门推荐
技术干货






