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

时间:2017-06-23 05:23:02

标签: python-3.x if-statement exception-handling nested file-not-found

您好我是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

1 个答案:

答案 0 :(得分:-2)

我希望你能找到这个:

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)
.
.

那就行了;)

并尝试下次正确解释您的问题,您并不完全清楚您想要做什么。