如何在功能之外将警告作为异常传递,但不会中断程序

问题描述 投票:0回答:1

我有一个实现模型和视图的程序。

我希望模型进行一些处理,如果出现问题,请向视图返回警告。

现在,我希望将警告作为一种异常传递出去,因此,如果我将GUI作为视图,则可以轻松地创建一个消息框或类似的东西来显示警告,但不会中断程序流。

有什么办法可以实现?

[注意:我知道Python中的warnings模块,但是我不知道我是否可以将那些警告作为不会中断程序流的异常来传递。

相关代码:

class Model():

   def __init__(self):
      try:
         with open(some_file) as file:
            self.file = file.readlines()
      except FileNotFoundError:
         # I don't want the Model to print the message here
         # print("Warning: File not found, continuing with defaults")
         # I want a warning to be passed up to the view
         self.file = 'some piece of data'
         raise FileNotFoundError(error_msg)
class View():

   def __init__(self):
      try:
         self.model = Model()
      except FileNotFoundError:
         # I want to catch the warning here and display it
         # but if I catch an exception here, Python will complain that
         # self.model was not initialized correctly when I use it later

谢谢

python python-3.x
1个回答
0
投票

异常用于委派错误处理,不与调用方通信。代替重新引发异常,向对象添加另一个属性,指示file属性中的数据是否经过硬编码。

例如,

class Model():

   def __init__(self):
      self.hard_coded = False
      try:
         with open(some_file) as file:
            self.file = file.readlines()
      except FileNotFoundError:
         self.source = True
         self.file = 'some piece of data'


class View():

   def __init__(self):
       self.model = Model()
       if self.hard_coded:
           print("Warning: File not found, continuing with defaults")

或者,您可以使用值为error_msg或字符串的None属性,以便在视图不是None时打印视图。

© www.soinside.com 2019 - 2024. All rights reserved.