Skip to content

Instantly share code, notes, and snippets.

@PandyYang
Created February 22, 2018 03:46
Show Gist options
  • Save PandyYang/8c33806d3bf6a41ab7a477d5270d59cc to your computer and use it in GitHub Desktop.
Save PandyYang/8c33806d3bf6a41ab7a477d5270d59cc to your computer and use it in GitHub Desktop.
#最简单的处理异常的方式
# try:
# x = int(input('Enter the first number:'))
# y = int(input('Enter the second number:'))
# print(x/y)
# except ZeroDivisionError:
# print("The second number can't be zero!")
#raise可以传递异常
# class MuffledCalculator:
# muffled = False
# def calc(self,expr):
# try:
# return eval(expr)
# except ZeroDivisionError:
# if self.muffled:
# print("Division by zero is illegal")
# else:
# raise
#可以使用多个except来返回错误类型
# try:
# x = int(input('Enter the first number:'))
# y = int(input('Enter the second number:'))
# print(x/y)
# except ZeroDivisionError:
# print("The second number can't be zero!")
# except TypeError:
# print("That wasn't a number,was it?")
#可以用一个块捕捉两个异常
# try:
# x = int(input('Enter the first number:'))
# y = int(input('Enter the second number:'))
# print(x/y)
# except (ZeroDivisionError,TypeError,NameError):
# print("Your number is bugos...")
#打印异常但是程序会继续进行
# try:
# x = int(input('Enter the first number:'))
# y = int(input('Enter the second number:'))
# print(x/y)
# except (ZeroDivisionError,TypeError)as e:
# print(e)
#实现全捕捉
# try:
# x = int(input('Enter the first number:'))
# y = int(input('Enter the second number:'))
# print(x/y)
# except:
# print("Some thing is Wrong")
#没有坏事发生时执行一段代码
try:
x = int(input('Enter the first number:'))
y = int(input('Enter the second number:'))
print(x/y)
except ZeroDivisionError:
print("The second number can't be zero!")
else:
print("Ah...It went as planned.")
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment