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