2012-02-02 35 views
0

我想用兩個不同的例外:多個除了一個嘗試

class toto: 
    def save(): 
    try:#gestion du cours 
     cours = Cours.objects.get(titre=self.titre, date=old_date) 
     cours.date = self.date 
     cours.save() 
    except Cours.DoesNotExist: 
     Cours.objects.create(titre=self.titre, date=self.date, valeur=self.cours) 
    except IntegrityError: 
     pass 

,但它不工作。 爲什麼?

編輯:固定intentation

+1

你能解釋一下什麼不是工作?你是否試圖在相同的情況下處理這兩個異常?還是你說有這些多個異常聲明不起作用? – jdi 2012-02-02 23:20:29

+0

正如所寫,這不是有效的代碼。你是否從你的實際代碼中剪切和粘貼?你是從前兩行獲得語法錯誤,還是你有其他問題? – 2012-02-02 23:34:43

+0

也許你想保存新創建的Cours對象? – WolframH 2012-02-03 00:54:40

回答

1

這擴展了@ arie的評論。

def save(): 
    obj,created = Cours.objects.get_or_create(titre=self.titre, date=old_date) 
    if created: 
     obj.date = self.date 
     obj.save() 

documentation

用於查找一個對象與給定kwargs, 如果需要創建一個的簡便方法。

返回(object,created)的元組,其中object是檢索到的或創建的對象,並且是一個布爾值,指定是否創建新的 對象。

如果你想趕上一個IntegrityError,只需將它放在一個嘗試:

try: 
    obj,created = Cours.objects.get_or_create(titre=self.titre, date=old_date) 
    if created: 
     obj.date = self.date 
     obj.save() 
except IntegrityError: 
    # do something 
+0

正是我所需要的 – francois 2012-02-05 20:29:31

0

在例外的邏輯是,如果一個異常在try塊拋出,然後嘗試捕獲在級聯製成。在你的情況,這是這樣的:

if try... throws an exception then: 
    if exception is Cours.DoesNotExist then: 
     Cours.objects.create(...) 
    else if exception is IntegrityError then: 
     pass 

這是你想要的?

1

我想我知道會發生什麼,IntegrityError正在異常部分引發。

嘗試,如果這能解決你的問題:

所有的
def save(): 
    try: #gestion du cours 
     cours = Cours.objects.get(titre=self.titre, date=old_date) 
     cours.date = self.date 
     cours.save() 
    except Cours.DoesNotExist: 
     try: 
      Cours.objects.create(titre=self.titre, date=self.date, valeur=self.cours) 
     except IntegrityError: 
      pass 
+0

這是一個有趣的事情,他可能會試圖做。我沒有想到他實際上試圖在create()方法上捕獲異常 – jdi 2012-02-02 23:34:37

+0

另外請注意,這種情況有一個快捷方式:https://docs.djangoproject.com/en/dev/ref/ models/querysets /#get-or-create – arie 2012-02-03 05:55:56

0

首先def totodef save()後之後,你已經失蹤:。縮進也是錯誤的。

最好先測試Cours.DoesNotExist,如果需要在try塊內創建。我不知道你的賽道是如何工作的,但更多的東西是這樣的:

class toto: 
    def save(): 
    try:#gestion du cours 
     try: 
     cours = Cours.objects.get(titre=self.titre, date=old_date) 
     except Cours.DoesNotExist as e: 
     print("trying to create " self.titre) 
     Cours.objects.create(titre=self.titre, date=self.date, valeur=self.cours) 
     # I guess you need this again now: 
     cours = Cours.objects.get(titre=self.titre, date=old_date) 
     cours.save() 
     cours.date = self.date 
    except Cours.DoesNotExist as e: 
     print("not even at second try: ",e) 
     raise 
    except IntegrityError: 
     pass 
    except BaseException as e: 
     print(" re-raise of some exception: ",type(e),e) 
     raise 

注意的順序,你捕獲的異常問題,如果一個測試異常是從另一個類。