python拋出異常方法


In [197]: float('1.2345')
Out[197]: 1.2345
In [198]: float('something')
---------------------------------------------------------------------------
ValueError Traceback (most recent <ipython-input-198-439904410854> in <module>()
----> 1 float('something')
ValueError: could not convert string to float: 'something'
1.
假如想優雅地處理float的錯誤,讓它返回輸⼊值。我們可以寫⼀
個函數,在try/except中調⽤float:
def attempt_float(x):
    try:
        return float(x)
    except:
        return x     
例子:
In [200]: attempt_float('1.2345')
Out[200]: 1.2345
In [201]: attempt_float('something')
Out[201]: 'something'

2.只想處理ValueError,TypeError錯誤(輸⼊不是字符串或
數值)可能是合理的bug。可以寫⼀個異常類型:

def attempt_float(x):
try:
return float(x)
except ValueError:
return x

例子:
1 def attempt_float(x):
2        try:
3             return float(x)
4         except ValueError:
5             return x
TypeError: float() argument must be a string or a number    

3.
可以⽤元組包含多個異常:
def attempt_float(x):
        try:
            return float(x)
        except (TypeError, ValueError):
        return x            

4.
某些情況下,你可能不想抑制異常,你想⽆論try部分的代碼是否
成功,都執⾏⼀段代碼。可以使⽤finally:
f = open(path, 'w')
    try:
        write_to_file(f)
    finally:
        f.close()

5.你可以⽤else讓只在try部分成功的情況下,才執⾏代碼:
f = open(path, 'w')
    try:
        write_to_file(f)
    except:
        print('Failed')
    else:
        print('Succeeded')
    finally:
        f.close()
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM