Python3 错误和异常

2017-03-28  本文已影响0人  Mr_ox

python3 有两种错误:语法错误和异常

1.语法错误

粗心导致,应尽量避免

2. 异常

运行期间检测到的错误被称为异常

3. 异常处理

  • try语句
while True:
        try:
            x = int(input("Please enter a number: "))
            break
        except ValueError:
            print("Oops!  That was no valid number.  Try again   ")
for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    else:  #若try执行过程中无异常,执行else语句中的内容           
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()  
 def divide(x, y):
        try:
            result = x / y
        except ZeroDivisionError:
            print("division by zero!")
        else:
            print("result is", result)
        finally:
            print("executing finally clause")
with open("myfile.txt") as f:
    for line in f:
        print(line, end="")
上一篇下一篇

猜你喜欢

热点阅读