第1段代码未使用try except,遇到异常退出,print('abc')未执行。执行结果如下
def func1(a,b):
return a/b
if __name__=='__main__':
func1(1,0)
print('abc')
D:\>python test_exception.py
Traceback (most recent call last):
File "test_exception.py", line 12, in <module>
func1(1,0)
File "test_exception.py", line 2, in func1
return a/b
ZeroDivisionError: integer division or modulo by zero
第2段代码使用try except,捕获到异常后继续执行print('abc')
def func1(a,b):
return a/b
if __name__=='__main__':
try:
func1(1,0)
except Exception as error:
print error
print('abc')
D:\>python test_exception.py
integer division or modulo by zero
abc
本文通过两个Python代码示例,详细解释了如何在代码中使用try-except语句来捕获并处理运行时错误,如除零错误。第一段代码在未使用异常处理的情况下,因除零错误导致程序崩溃;而第二段代码则通过try-except成功捕获异常,并继续执行后续代码,展示了异常处理的重要性。
1万+





