Python 全部包含异常
Python all encompassing exception
我正在查看 python 中有一个 try: except Exception
块的代码。我已经确定了可能引发 ValueError
.
我的问题:将 ValueError
包含在except
子句(除了已经包含 ValueError
的 Exception
之外)?
try:
func_raises_value_error()
func_raises_unknown_error()
except (ValueError, Exception) as e:
pass
捕获特定错误绝对是个好习惯。使用 try: except:
有两个一般准则:
- 保持
try
块尽可能短;和
- 尽可能具体说明您要处理的错误。
所以而不是例如
try:
print("Please enter your name")
name = input(" > ")
print("Please enter your age")
age = int(input(" > "))
print("{} is {} years old".format(name, age))
except Exception:
print("Something went wrong")
你应该有:
print("Please enter your name")
name = input(" > ")
print("Please enter your age")
try:
age = int(input(" > "))
except ValueError:
print("That's not a number")
else:
print("{} is {} years old".format(name, age))
请注意,这允许更具体的错误消息,并允许将任何未预料到的错误传递给调用者(根据 the Zen of Python:"Errors should never pass silently. Unless explicitly silenced." )
在您的具体情况下,使用 except (ValueError, Exception) as e:
没有意义,原因有二:
Exception
已经包含 ValueError
;和
- 您实际上并没有使用
e
做任何事情。
如果您无法(或不想)对任何一个函数引发的错误做些什么,您不妨使用 except Exception:
(这比裸露的 except:
好,在最少)。
处理一个代码块中可能出现的多个异常时,一个好习惯是从最具体的异常到最一般的异常进行处理。
例如,您的代码可以写成:
try:
func_raises_value_error()
func_raises_unknown_error()
except ValueError as e:
print 'Invalid value specified: %s' % e
except Exception as e:
print 'A totally unexpected exception occurred: %s' % e
我正在查看 python 中有一个 try: except Exception
块的代码。我已经确定了可能引发 ValueError
.
我的问题:将 ValueError
包含在except
子句(除了已经包含 ValueError
的 Exception
之外)?
try:
func_raises_value_error()
func_raises_unknown_error()
except (ValueError, Exception) as e:
pass
捕获特定错误绝对是个好习惯。使用 try: except:
有两个一般准则:
- 保持
try
块尽可能短;和 - 尽可能具体说明您要处理的错误。
所以而不是例如
try:
print("Please enter your name")
name = input(" > ")
print("Please enter your age")
age = int(input(" > "))
print("{} is {} years old".format(name, age))
except Exception:
print("Something went wrong")
你应该有:
print("Please enter your name")
name = input(" > ")
print("Please enter your age")
try:
age = int(input(" > "))
except ValueError:
print("That's not a number")
else:
print("{} is {} years old".format(name, age))
请注意,这允许更具体的错误消息,并允许将任何未预料到的错误传递给调用者(根据 the Zen of Python:"Errors should never pass silently. Unless explicitly silenced." )
在您的具体情况下,使用 except (ValueError, Exception) as e:
没有意义,原因有二:
Exception
已经包含ValueError
;和- 您实际上并没有使用
e
做任何事情。
如果您无法(或不想)对任何一个函数引发的错误做些什么,您不妨使用 except Exception:
(这比裸露的 except:
好,在最少)。
处理一个代码块中可能出现的多个异常时,一个好习惯是从最具体的异常到最一般的异常进行处理。 例如,您的代码可以写成:
try:
func_raises_value_error()
func_raises_unknown_error()
except ValueError as e:
print 'Invalid value specified: %s' % e
except Exception as e:
print 'A totally unexpected exception occurred: %s' % e