2012-11-05 28 views
-3

這是我下面的程序OverflowError例外,在巨蟒沒有檢測

try: 
    class __Euler3__: 
    n = 600851475143 
    primeFactors = [] 

    for i in range(2,n): 
     if (n%i ==0): 
      primeFactors.append(i) 
      n = n/i 
      i = i -1 #reset i 
      print primeFactors 

except OverflowError as e: 
     print "the error is" , e 

,但由於某些原因Overflowerror機制不能夠趕上這個異常 我使用Python 2.7

+1

你的縮進被搞砸了,'class __Euler3__'的目的是什麼? – mgilson

+0

你在什麼時候期待異常? –

+0

您的代碼不可讀。我無法檢測縮進。 – alexvassel

回答

4

OverflowError升高,當你不能代表數字,因爲它太大了。 python整數不會發生這種情況(因爲它們在變得太大時會無縫地變成long,而在python3中,所有整數都是long,即任意精度)。

documentation直報價(加上一些重點):

Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for long integers (which would rather raise MemoryError than give up) and for most operations with plain integers, which return a long integer instead. Because of the lack of standardization of floating point exception handling in C, most floating point operations also aren’t checked.

0

由於mgilson指出,沒有OverflowError提高。在未來,如果你想檢查代碼是否自行退出或工作,你可以使用try /除/其他:

try: 
    foo() 
    baz() 
except: 
    print "error" 
else: 
    print "no error!" 
+0

當然在這種情況下,它可能會運行很長時間(特別是一旦交換開始顛簸)他永遠不會看到結果,但它仍然是一個有用的技巧。除非你真的應該這樣做'除了Exception:e:print「error:」,e'而不是'except:print「error」'。 (這是你要發現的唯一方法,例如,你得到的是不同於你預期的異常類型)。 – abarnert