python 学习---错误 & 异常1

1. 错误&异常概述

获取BaseException

1 #!/usr/bin/env python3
2 # -*- encoding: utf-8 -*-
3 def classtree(cls, indent=0):
4     print('.' * indent, cls.__name__)
5     for subcls in cls.__subclasses__():
6         classtree(subcls, indent + 3)
7 
8 classtree(BaseException)

2. Try except 语法详解

代码示例:

1 #!/usr/bin/env python3
2 # -*- encoding: utf-8 -*-
3 while True:
4     try:
5         x = float(input("Please enter a number:"))
6         break
7     except ValueError:
8         print("Oops! That was no valid number. Try again...")
9         continue
 1 #!/usr/bin/env python3
 2 # -*- encoding: utf-8 -*-
 3 def main():
 4     try:
 5         number1, number2 = eval(input("Enter two numbers, separated by a comma:"))
 6         result = number1 / number2
 7 
 8     except ZeroDivisionError:
 9         print("Division by zero!")
10     except SyntaxError:
11         print("A comma may be missing in the input")
12     except:
13         print("Something wrong in the input")
14     else:
15         print("No exceptions, the result is", result)
16     finally:
17         print("executing the final clause")
18 
19 main()
原文地址:https://www.cnblogs.com/hayden1106/p/7767045.html