Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 更改file.index的默认值错误_Python_Python 2.7_Error Handling - Fatal编程技术网

Python 更改file.index的默认值错误

Python 更改file.index的默认值错误,python,python-2.7,error-handling,Python,Python 2.7,Error Handling,我使用file.index在文件中搜索字符串 def IfStringExistsInFile(self,path,lineTextCheck): file = open(path).read() if file.index(lineTextCheck): print (lineTextCheck + " was found in: " + path) else: raise ValueError (lineTextCheck + " wa

我使用file.index在文件中搜索字符串

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的else代码:

ValueError: substring not found
有没有办法更改默认值错误

目前,我想到的唯一方法是用try-except来包装句子,如下所示:

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)

如果有更好的办法,我们将不胜感激。提前谢谢你

据我所知,您无法更改内置错误。当你提出一个错误时,你可以在任何你想要的地方提出它,但是因为你做了,除了内置的错误,你仍然会得到它


因此,我认为你的第二个解决方案是最好的,除了内置的错误,然后用加薪来处理它,据我所知,你不能改变内置的错误。当你提出一个错误时,你可以在任何你想要的地方提出它,但是因为你做了,除了内置的错误,你仍然会得到它

因此,我认为你的第二个解决方案是最好的,除了固有的错误,并以加薪的方式对待它

如果有更好的办法,我们将不胜感激

你解决了这个问题,这应该怎么解决

请注意,您可以通过创建从BaseException继承的类来创建自己的异常,但这很少需要

如果有更好的办法,我们将不胜感激

你解决了这个问题,这应该怎么解决

请注意,您可以通过创建从BaseException继承的类来创建自己的异常,但这很少需要。

使用try/except是标准做法。如果是这样,如果找到索引而没有引发错误,则可以删除该行:

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

使用try/except是标准做法。如果是这样,如果找到索引而没有引发错误,则可以删除该行:

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