簡體   English   中英

如何在 Python 3.3 中引發異常

[英]How to raise an exception in Python 3.3

我目前正在閱讀 tutorialspoint 的 python 教程中的教程。 但這是 Python 2 的教程,而不是我現在擁有的 Python 3.3。 嗯,我設法在互聯網上搜索並發現了一些變化。 但這一關相當艱難。

因此,在 tutorialspoint 中,引發異常的 python 源代碼是:

def functionName( level ):
if level < 1:
   raise "Invalid level!", level
  # The code below to this would not be executed
  # if we raise the exception

但是如果我輸入

raise "Invalid level!", level  

它說語法錯誤。 所以,我想知道如何在 Python 3.3 中引發異常。

語法是:

raise Exception("Invalid level! " + level)

我真的建議您閱讀Python 文檔。

您需要創建一個異常對象:

 raise Exception('spam', 'eggs')

請參閱此處的文檔: http : //docs.python.org/3/tutorial/errors.html#handling-exceptions

作為參考,這里有一個簡單的例子:

# Raise exception if x != 4
try:
    x = 3
    if (x != 4):
        raise Exception('X is not 4')
except Exception as e:
    print('ERROR: ', e)

暫無
暫無

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

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