-
打开你的 VS Code 编辑器。
-
在 ~/project
目录下创建一个名为 exception_classes.py
的新文件。
~/project/exception_classes.py
-
在 exception_classes.py
文件中添加以下代码:
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Caught a ZeroDivisionError:", e)
except ArithmeticError as e:
print("Caught an ArithmeticError:", e)
except Exception as e:
print("Caught some other exception:", e)
print("Program continues...")
在这个脚本中,我们尝试将 10 除以 0,这将引发一个 ZeroDivisionError
异常。我们有三个 except
块:一个用于 ZeroDivisionError
,一个用于 ArithmeticError
,还有一个用于 Exception
。
-
在终端中使用以下命令运行脚本:
python exception_classes.py
这将在终端中打印出 "Caught a ZeroDivisionError: division by zero"。
示例输出:
Caught a ZeroDivisionError: division by zero
Program continues...
输出结果表明,ZeroDivisionError
被第一个 except
块捕获。
现在,让我们修改脚本以引发不同的异常。
-
将 exception_classes.py
文件修改为以下内容:
try:
result = int("abc")
except ZeroDivisionError as e:
print("Caught a ZeroDivisionError:", e)
except ValueError as e:
print("Caught a ValueError:", e)
except ArithmeticError as e:
print("Caught an ArithmeticError:", e)
except Exception as e:
print("Caught some other exception:", e)
print("Program continues...")
在这个修改后的脚本中,我们尝试将字符串 "abc" 转换为整数,这将引发一个 ValueError
异常。
-
再次使用相同的命令运行脚本:
python exception_classes.py
这将在终端中打印出 "Caught a ValueError: invalid literal for int() with base 10: 'abc'"。
示例输出:
Caught a ValueError: invalid literal for int() with base 10: 'abc'
Program continues...
这个输出表明,ValueError
被第二个 except
块捕获。
通过在 except
块中直接指定异常类,你可以清晰、有条理地处理不同类型的异常。对于简单的异常处理,这种方法通常比使用 isinstance()
更受青睐。