8.3.6 万事大吉时
在有些情况下,在没有出现异常时执行一个代码块很有用。为此,可像条件语句和循环一样,给try/except语句添加一个else子句。
try:
print('A simple task')
except:
print('What? Something went wrong?')
else:
print('Ah ... It went as planned.')
如果你运行这些代码,输出将如下:
A simple task
Ah ... It went as planned.
通过使用else子句,可实现8.3.3节所说的循环。
while True:
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
value = x / y
print('x / y is', value)
except:
print('Invalid input. Please try again.')
else:
break
在这里,仅当没有引发异常时,才会跳出循环(这是由else子句中的break语句实现的)。换而言之,只要出现错误,程序就会要求用户提供新的输入。下面是这些代码的运行情况:
Enter the first number: 1
Enter the second number: 0
Invalid input. Please try again.
Enter the first number: 'foo'
Enter the second number: 'bar'
Invalid input. Please try again.
Enter the first number: baz
Invalid input. Please try again.
Enter the first number: 10
Enter the second number: 2
x / y is 5
前面说过,一种更佳的替代方案是使用空的except子句来捕获所有属于类Exception(或其子类)的异常。你不能完全确定这将捕获所有的异常,因为try/except语句中的代码可能使用旧式的字符串异常或引发并非从Exception派生而来的异常。然而,如果使用except Exception as e,就可利用8.3.4节介绍的技巧在这个小型除法程序中打印更有用的错误消息。
while True:
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
value = x / y
print('x / y is', value)
except Exception as e:
print('Invalid input:', e)
print('Please try again')
else:
break
下面是这个程序的运行情况:
Enter the first number: 1
Enter the second number: 0
Invalid input: integer division or modulo by zero
Please try again
Enter the first number: 'x' Enter the second number: 'y'
Invalid input: unsupported operand type(s) for /: 'str' and 'str'
Please try again
Enter the first number: quuux
Invalid input: name 'quuux' is not defined
Please try again
Enter the first number: 10
Enter the second number: 2
x / y is 5
领取专属 10元无门槛券
私享最新 技术干货