Python raise 關鍵字



Python 的raise關鍵字用於引發異常。Try-exception 塊可以管理異常。它通常用於函式或方法內部,用於指示錯誤狀態。

我們必須處理異常,因為它可能會導致軟體崩潰並顯示錯誤訊息。

語法

以下是 Python raise關鍵字的語法:

raise

示例

以下是 Python raise關鍵字的基本示例:

# Input
x = -1
# Use of "raise"
if x < 100:
    raise Exception("Sorry, number is  below zero")

以下是上述程式碼的輸出:

Traceback (most recent call last):
  File "/home/cg/root/56605/main.py", line 5, in <module>
    raise Exception("Sorry, number is  below zero")
Exception: Sorry, number is  below zero

使用 'raise' 關鍵字和 try-exception

raise關鍵字可以與 try-except 塊一起使用。它將返回由 raise 關鍵字引發的異常。

示例

這裡,我們使用在函式divide()內部定義的raise關鍵字引發了一個異常。當除數為零時,此函式將引發異常:

def divide(a, b):  
    if b == 0:  
        raise Exception("Cannot divide by zero. ")  
    return a / b  
try:  
    result = divide(1, 0)  
except Exception as e:  
    print(" An error occurred :",e)  

輸出

以下是上述程式碼的輸出:

An error occurred : Cannot divide by zero. 

使用 'raise' 關鍵字和 'finally'

無論raise關鍵字是否引發異常,finally塊都將執行。

示例

def variable(a,b):  
    if b == 'zero':  
        raise Exception("Sorry we cannot divide with string")  
    return a/b  
try:  
    result = variable(1,'zero')
    print(result) 
except Exception as e:  
    print("Error occurred: ", e)  	
finally:
    print("This is statement is executed irrespective") 

輸出

以下是上述程式碼的輸出:

Error occurred:  Sorry we cannot divide with string
This is statement is executed irrespective
python_keywords.htm
廣告