一.异常处理语句
1.格式1
异常处理语句
try:
<body>
except <ErrorType1>:
<handler1>
except <ErrorType2>:
<handler2>
except <ErrorType3>:
<handler3>
else:#如果没有异常则执行这个语句
<process_else>
finally:#不管有没有异常都要执行
<process_finaly>
样例1:
def main():
try:
num1,num2=eval(input('Enter two numbers,separated by a comma:'))
result=num1/num2
except ZeroDivisionError:
print('Division by zero!')
except SyntaxError:
print('A comma may be missing in the input')
except:
print('Something wrong in the input')
else:
print('No exceptions,the result is',result)
finally:
print('executing the final clause')
main()
运行结果:
====================== RESTART: D:\python3.6\divnum.py ======================
Enter two numbers,separated by a comma:1,2
Something wrong in the input
executing the final clause
>>>
====================== RESTART: D:\python3.6\divnum.py ======================
Enter two numbers,separated by a comma:1,0
Something wrong in the input
executing the final clause
>>>