2016-11-29 95 views
0

我知道我不清楚這件事,但我不能在標題中更具體。請看下面的代碼:Python:假實際嘗試之前嘗試和發現異常

try: 
    print "Try this out" 
    a = int("Blah blah") 
except: 
    print "I got the exception" 

這段代碼的輸出是─

Try this out 
I got the exception 

我想要什麼蟒蛇做的是檢查,如果它有可能引起在嘗試一個例外:塊,然後再執行它。否則,只需執行except:block。如果不嵌套多個try-except塊,可以做這樣的事情嗎?

+0

爲什麼你要做這樣的事情?這違背了[EAFP]的Python哲學(https://docs.python.org/2/glossary.html)。 –

+0

這個問題或目的不是很清楚。你會怎麼做嵌套塊?你想要'僞跑'有副作用嗎?在執行引發異常的代碼之前,你能先檢查一個條件嗎?這聽起來更像你想要做的。 – theorifice

+0

Python是完全動態類型的。我認爲你指的是諸如Java這樣的語言,其中函數可以在其函數聲明結尾處用'throws SomeExceptionType'標記。 Python不是這樣的。您會在運行時收到異常,並且無法確定它是否會(甚至可以)拋出。 – Goodies

回答

0

不,這是不可能的,因爲你在執行過程中遇到異常。但是你可以這樣做:

try: 
    a = int("Blah blah") 
    print "Try this out" 
except: 
    print "I got the exception" 
0

你try語句的打印速度,因爲沒有錯誤打印它發生,但只要它試圖執行a,得到一個錯誤,以便except執行。

試試這個辦法趕上正確的異常:

try: 
    a = int("Blah blah") 
    print ("Try this out") 

except: 
    print ("I got the exception") 
+0

這不符合我的目的。看到我對這個問題的最後評論... –