簡體   English   中英

如何在 PyQt 中正確管理異常

[英]How to manage exceptions correctly in PyQt

我想知道如何在 pyqt 中管理多個異常

我有一個函數 'encodeVideo()' 可能會觸發多個異常。

def updateFilename(self):
    try:
        self.model.updateFilename(self.fileName)
    except type_exc.PathIsEmpty as e:
        self.errorDialog.errorTypeChanged(e)
        self.errorDialog.show()

def updateOutput(self):
    try:
        self.model.updateOutput(self.encodeDialog.output)
    except (type_exc.FileAlreadyExists,  type_exc.PathNotExists) as e:
        self.errorDialog.errorTypeChanged(e)
        self.errorDialog.show()

def encodeVideo(self):
    self.updateFilename()
    self.updateOutput()

就我而言,它可能會在updateFilname()updateOutput觸發錯誤。 發生這種情況時,會出現一個對話框並報告兩個錯誤。 但是,我似乎以錯誤的方式管理異常。 例如,當self.updateFilename()發生錯誤時,這不會阻止我的代碼繼續下一個代碼self.updateOutput()

您希望在方法調用堆棧中盡可能高地處理異常; 這通常意味着異常是在第一次調用的 UI 中處理的,如果在您的任何方法中您需要在發生異常時執行某些操作,您應該捕獲並重新拋出異常,以下是一些示例:

在您的代碼中,從 UI 調用的第一個方法是encodeVideo ,因此,您希望在那里捕獲和處理您的異常:

def updateFilename(self):
    self.model.updateFilename(self.fileName)

def updateOutput(self):
    self.model.updateOutput(self.encodeDialog.output)

def encodeVideo(self):
    try:
        self.updateFilename()
        self.updateOutput()
    except (type_exc.PathIsEmpty, type_exc.FileAlreadyExists,  type_exc.PathNotExists) as e:
        self.errorDialog.errorTypeChanged(e)
        self.errorDialog.show()

重新拋出異常

讓我們想象一下,如果對updatedOutput的調用失敗,您想要做一些特定的事情,在這種情況下,您可以在內部方法中處理異常,但您應該再次拋出它,以便由調用方法處理:

def updateOutput(self):
    try:
        self.model.updateOutput(self.encodeDialog.output)
    except type_exc.FileAlreadyExists, e:
        print("Do something")
        raise type_exc.FileAlreadyExists(e)

def encodeVideo(self):
    try:
        self.updateFilename()
        self.updateOutput()
    except (type_exc.PathIsEmpty, type_exc.FileAlreadyExists,  type_exc.PathNotExists) as e:
        self.errorDialog.errorTypeChanged(e)
        self.errorDialog.show()

這基本上是一個異常和錯誤處理問題。 因此,如果任何塊中存在錯誤,則系統會將其作為錯誤句柄或異常句柄。 因此,如果第一個代碼塊給出 error ,那么下一個塊包含另一個處理程序異常,因此系統將其視為錯誤和異常塊非常簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM