2016-07-11 47 views
1

我正在使用file.index在文件中搜索字符串。更改file.index的默認值ValueError

def IfStringExistsInFile(self,path,lineTextCheck): 
    file = open(path).read() 
    if file.index(lineTextCheck): 
     print (lineTextCheck + " was found in: " + path) 
    else: 
     raise ValueError (lineTextCheck + " was NOT found in: " + path) 

我的問題是,如果沒有找到該字符串,它會自動提高默認ValueError異常,並不會進入其中包含我的自定義ValueError異常的「其他」代碼:

ValueError: substring not found 

有我可以改變這個默認的ValueError的方法?

目前,我想出的唯一辦法是換句用「嘗試除」,就像這樣:

def IfStringExistsInFile(self,path,lineTextCheck): 
    file = open(path).read() 
    try: 
     if file.index(lineTextCheck): 
      print (lineTextCheck + " was found in: " + path) 
    except: 
      raise ValueError(lineTextCheck + " was NOT found in: " + path) 

沒有更好的辦法,將不勝感激。先謝謝你!

回答

1

據我所知你不能改變內置的錯誤。當你raise出現一個錯誤時,你會將它提升到任何你想要的位置,但是因爲你完成了except這個內置錯誤,你仍然會得到這個錯誤。

所以你的第二個解決方案是我認爲最好的,以except內置的錯誤,並且解決它究竟應如何解決與raise

2

Any better way would be greatly appreciated

對待它。

請注意,您可以創建自己的Exception,方法是創建一個繼承自BaseException的類,但這很少需要。

+0

完美,謝謝:) –

1

Easier to Ask for Forgiveness than Permission。使用try/except這是標準做法。您也可以丟棄if因此,如果索引找到的行會打印不提高錯誤:

try: 
    file.index(lineTextCheck) 
    print (lineTextCheck + " was found in: " + path) 
except ValueError: # explicitly specify the error 
    raise ValueError(lineTextCheck + " was NOT found in: " + path) 
+0

卸下「如果」是一個很好的改良效果,謝謝! –