python return try catch_如何捕获Try/catch块Python中的所有异常?

使用一个块可以捕获多个异常。让我们对异常使用异常和算术错误。try:

# Do something

print(q)

# Catch exceptions

except (Exception, ArithmeticError) as e:

template = "An exception of type {0} occurred. Arguments:\n{1!r}"

message = template.format(type(e).__name__, e.args)

print (message)

如果您需要捕获几个异常并单独处理每个异常,那么您将为每个异常编写一个except语句。try:

# Do something

print(q)

# Catch exceptions

except Exception as e:

print (1)

except ArithmeticError as e:

print (2)

# Code to be executed if the try clause succeeded with no errors or no return/continue/break statement

else:

print (3)

您还可以检查异常是否属于“MyCustomException”类型,例如使用if语句。if isinstance(e, MyCustomException):

# Do something

print(1)

至于你的问题,我建议把代码分成两个函数。install(required_libraries)

def install(required_libraries, version='pip2.7'):

# Perform installation

try:

from subprocess import check_output

pip27_path = subprocess.check_output(['sudo','find','/','-name', version])

lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]

except Exception as e:

backup(required_libraries)

def backup(required_libraries, version='pip2.6'):

try:

p = subprocess.Popen(['sudo','find','/','-name',version]], stdout=subprocess.PIPE);pip26_path, err = p.communicate()

lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]

except Exception as e:

template = "An exception of type {0} occurred. Arguments:\n{1!r}"

message = template.format(type(e).__name__, e.args)

print (message)

#Handle exception

注:我没有测试这个,我也不是专家,所以我希望我能帮忙。

有用的链接:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值