try-except
try:
num = int(input("Please input a number:\n"))
print(42 / num)
except ZeroDivisionError:
print("Divided by zero!")
except ValueError:
print("Wrong value!")
def division(DivideBy):
return 42 / DivideBy
try:
print(division(1))
print(division(0))
print(division(7))
except ZeroDivisionError:
print("Divided by zero!")
- 运行结果:

try-except-else
- 和try-except类似,不过如果程序没有错误,也就是没有跳到except语句块,则执行else语句块,如果程序发生错误,即跳到except语句块,则直接跳过else语句块
- 示例程序:
def division(DivideBy):
return 42 / DivideBy
try:
num = int(input("Please input a integer:\n"))
print(division(num))
except ZeroDivisionError:
print("Divided by zero!")
except ValueError:
print("Wrong input!")
else:
print("No error. Good job!")
try-finally
def division(DivideBy):
return 42 / DivideBy
try:
num = int(input("Please input a integer:\n"))
print(division(num))
except ZeroDivisionError:
print("Divided by zero!")
except ValueError:
print("Wrong input!")
else:
print("No error. Good job!")
finally:
print("Finished")
- 运行结果:
 
|