Python : 捕获到异常后如何停止执行?
Python : How to stop execution after exception has been caught?
我有一个 class dataset.py,它有很多功能,还有一个记录器,看起来像:
class dataset:
def get_data():
try:
if(sourcefile != None):
if not os.path.isfile(sourceFile):
raise FileNotFoundError
except FileNotFoundError:
logger.error('File not found!')
def do_something():
return
我按以下方式使用这些 class:
datasetObj = dataset()
datasetObj.get_data()
datasetObj.do_something()
现在,即使 get_data() 引发 FileNotFoundError,它也会在 except 块中处理,程序继续转到 do_something()。
我该如何阻止它?如果存在文件未找到错误,则执行应停止。
我如何 return 我对调用者的异常并使我的 main.py 不再执行?
你可以做几件事。
import sys # top of your code
sys.exit(1)
我相信您也可以立即提出异常:
raise
登录 except
后立即执行此操作
我有一个 class dataset.py,它有很多功能,还有一个记录器,看起来像:
class dataset:
def get_data():
try:
if(sourcefile != None):
if not os.path.isfile(sourceFile):
raise FileNotFoundError
except FileNotFoundError:
logger.error('File not found!')
def do_something():
return
我按以下方式使用这些 class:
datasetObj = dataset()
datasetObj.get_data()
datasetObj.do_something()
现在,即使 get_data() 引发 FileNotFoundError,它也会在 except 块中处理,程序继续转到 do_something()。
我该如何阻止它?如果存在文件未找到错误,则执行应停止。 我如何 return 我对调用者的异常并使我的 main.py 不再执行?
你可以做几件事。
import sys # top of your code
sys.exit(1)
我相信您也可以立即提出异常:
raise
登录 except
后立即执行此操作