美文网首页
Python3 错误和异常

Python3 错误和异常

作者: Mr_ox | 来源:发表于2017-03-28 17:04 被阅读0次

    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()  
    
    • 抛出异常:raise
    • 自定义异常
    • 定义清理行为:finally
     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
    with open("myfile.txt") as f:
        for line in f:
            print(line, end="")
    

    相关文章

      网友评论

          本文标题:Python3 错误和异常

          本文链接:https://www.haomeiwen.com/subject/ciojottx.html