2016-05-18 67 views
-2

我遇到了ValueError以我想要的方式工作的問題。值錯誤和字符串異常

我有一個是返回一個字符串的函數,但我不希望它太評估爲一個ValueError如果不從功能提出

示例代碼

def test(a): 
    if a == a: 
     raise ValueError('There was a error # 2') 


a = 'a' 
if ValueError: 
    print "There was a error # 1" 


test(a) 

輸出

There was a error # 1 
Traceback (most recent call last): 
    File "/home/user/Test_1.py", line 13, in <module> 
    test(a) 
    File "/home/user/Test_1.py", line 5, in test 
    raise ValueError('There was a error # 2') 
ValueError: There was a error # 2 

Process finished with exit code 1 

如果我正確地閱讀文檔說它可以提出b我是一個字符串,我如何防止這種行爲?

https://docs.python.org/2/library/exceptions.html#exceptions.IndexError

+2

1)'如果ValueError'永遠爲真和'print'將總是被執行。 2)你的函數總是會引發錯誤,因爲「如果a == a」總是如此。 3)你沒有做任何事情來捕捉錯誤。 - 我很不清楚你想在這裏做什麼。也許你正在尋找'try..catch'語法...?! – deceze

回答

-1

不知道爲什麼它之前的工作,但我做到更加明確,現在的工作。此外,第一個示例更加模糊,我試圖從庫中的函數中捕獲錯誤。

示例代碼

def test(a): 
    try: 
     if a == a: 
      pass 
     raise ValueError('There was a error # 2') 
    except Exception, e: 
     str(e) 
     return e 

a = 'a' 

b = test(a) 

if type(b) == ValueError: 
    print b 

輸出

There was a error # 2 

Process finished with exit code 0 
+0

@deceze下面是答案 – sonance207

+0

這段代碼仍然是廢話。我不知道它應該完成什麼。 – deceze