如何捕获错误并停止使用 IF 和 ELSE 语句?

How to catch error and stop using IF and ELSE statement?

您好,我是 python 编程新手。我是通过做项目自学的。

下面的代码工作正常,但我想在条件为 FALSE 时捕获异常。如果目录不存在,我已经有一个要打印的声明;并继续。我知道我可以通过嵌套 if 语句来使这段代码工作。

但我不想这样做。我想继续下一行代码。当我 运行 按原样显示时,如果目录丢失,我将收到错误消息。

import os
goToDir = open("URPsetup.dat","r")
goToDirPath = goToDir.read()

if (os.path.exists(goToDirPath))== True:
os.chdir(goToDirPath)
else: print("directory not found, please check file URPsetup.dat")

goToConfig = open("utility.dat", "r")
print(goToConfig.read())

当目录不存在时,我收到此错误消息。我的意思是,我在 "URPsetup.dat" 中提供的目录不正确。我这样做是为了看看代码是否会在上面的 else 语句处停止。它将打印 else 语句,并继续显示下面的错误消息。我如何捕获此错误并停止?

directory not found, please check file URPsetup.dat
Traceback (most recent call last):
File "C:/Users/R82436/PycharmProjects/URP2017/prototype.py", line 9, in     <module>
goToConfig = open("utility.dat", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'utility.dat'
directory not found, please check file URPsetup.dat

Process finished with exit code 1

我猜你正在寻找这个:

import sys
.
.
else: 
    print("directory not found, please check file URPsetup.dat")
    sys.exit()
.
.

或者这也可以:

# No need to import sys
.
.
else: 
    print("directory not found, please check file URPsetup.dat")
    raise SystemExit(0)
.
.

那就行了;)

并且下次尝试正确解释你的问题,你并不完全清楚你到底想做什么。