如何在PYTHON里捕获和抛出异常
1、result = int(input("What is the result when 1 plus 1?"))
#这里需要用户输入整数,但是这里却是字符,那么就显示出错。

2、try:
result = int(input("What is the result when 1 plus 1?"))
except:
print("The value is wrong!")
except Exception as i:
print("This is unknow error %s. " % i)
print("The end!")
#如果不知道还会有什么异常可以用Exception,但是这里出错是因为单独except要放在后面。

3、try:
result = int(input("What is the result when 1 plus 1?"))
except Exception as result:
print("This is unknow error %s. " % result)
except:
print("The value is wrong!")
print("The end!")
#这个时候就可以排除所有错误了。

4、try:
result = int(input("What is the result when 1 plus 1?"))
except Exception as result:
print("This is unknow error %s. " % result)
else:
print("No error!")
finally:
print("The end!")
#可以在后面加上else,如果没有错误就会运行,形成try...else语句。

5、try:
result = int(input("What is the result when 1 plus 1?"))
except Exception as result:
print("This is unknow error %s. " % result)
else:
print("No error!")
finally:
print("The end!")
#但是如果有异常else不会运行。但是finally是会运行的。

6、def test1():
return int(input("What is the result when 1 plus 1?"))
test1()
#这里可以看出发现异常系统没有马上终止,而是先进行传递。

7、def test1():
return int(input("What is the result when 1 plus 1?"))
try:
test1()
except Exception as result:
print("somthing is wrong %s. " % result)
#面对这种情况也是可以在最后面加上try和except来捕获异常。

8、def test():
result = int(input("What is the result when 1 plus 1?"))
if result.isalpha():
return result
print("there is an error.")
error = Exception("输入错误")
raise error
test()
#我们可以主动捕获异常。

9、def test():
result = input("What is the result when 1 plus 1?")
if len(result) == 1:
return result
print("there is an error.")
error = Exception("输入错误")
raise error
try:
print(test())
except Exception as result:
print(result)
#设置try和except在下方,然后正常运行一下。

10、def test():
result = input("What is the result when 1 plus 1?")
if len(result) == 1:
return result
else:
print("there is an error.")
raise Exception("输入错误")
try:
print(test())
except Exception as result:
print(result)
#这个时候就可以在有错误的时候捕获到异常。先运行,有错误的话捕获异常,并且在except里面把异常当结果输出。
