[英]PYTHON : How to catch exception for multiple validation in try block?
如何在單個try塊中捕獲多個驗證的異常? 有可能還是我需要使用多個try塊? 這是我的代碼:
import sys
def math_func(num1, num2):
return num1*num2
a,b = map(str,sys.stdin.readline().split(' '))
try:
a = int(a)
b = int(b)
print("Result is - ", math_func(a,b), "\n")
except FirstException: # For A
print("A is not an int!")
except SecondException: # For B
print("B is not an int!")
Python相信顯式的異常處理。 如果您只是想知道哪條線會導致異常,那么不要進行多次異常處理。 在您的情況下,您不需要單獨的異常處理程序,因為您不會基於引發異常的特定行進行任何條件操作。
import sys
import traceback
def math_func(num1, num2):
return num1*num2
a,b = map(str, sys.stdin.readline().split(' '))
try:
a = int(a)
b = int(b)
print("Result is - ", math_func(a,b), "\n")
except ValueError:
print(traceback.format_exc())
這將打印導致錯誤的行
您確實可以在一個塊中捕獲兩個異常,這可以像這樣完成:
import sys
def mathFunc(No1,No2):
return No1*No2
a,b = map(str,sys.stdin.readline().split(' '))
try:
a = int(a)
b = int(b)
print("Result is - ",mathFunc(a,b),"\n")
except (FirstException, SecondException) as e:
if(isinstance(e, FirstException)):
# put logic for a here
elif(isinstance(e, SecondException)):
# put logic for be here
# ... repeat for more exceptions
您也可以簡單地捕獲一個通用的Exception
,這對於在運行時必須維護程序執行時非常方便,但是最好的方法是避免這種情況並捕獲特定的異常
希望這可以幫助!
可能與此重復嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.