在Python中,錯誤處理主要通過異常處理機制來實現
try-except
語句捕獲異常:def find_function(value):
try:
# 可能引發異常的代碼
result = 10 / value
except ZeroDivisionError:
print("Error: Division by zero")
return None
except Exception as e:
print(f"Error: {e}")
return None
else:
return result
# 調用find_function
result = find_function(0)
if result is not None:
print(f"Result: {result}")
try-except-else-finally
語句處理多種異常:def find_function(value):
try:
# 可能引發異常的代碼
result = 10 / value
except ZeroDivisionError:
print("Error: Division by zero")
return None
except TypeError:
print("Error: Invalid input type")
return None
else:
return result
finally:
print("Function execution completed")
# 調用find_function
result = find_function("a")
if result is not None:
print(f"Result: {result}")
class CustomError(Exception):
pass
def find_function(value):
if value == "error":
raise CustomError("Custom error occurred")
return 10 / value
try:
result = find_function("error")
except CustomError as e:
print(f"Error: {e}")
assert
語句進行調試:def find_function(value):
assert value != 0, "Division by zero"
return 10 / value
try:
result = find_function(0)
except AssertionError as e:
print(f"Error: {e}")
請根據您的需求選擇合適的錯誤處理策略。在實際編程中,建議使用try-except
語句來捕獲和處理異常,以確保程序的穩定性和健壯性。