zoukankan      html  css  js  c++  java
  • Python文件_捕获异常

    捕获异常

    1.读写文件的时候有很多容易出错的地方;如果你要打开的文件不存在,就会得到一个IOerror:

    >>> find = open('bad_file.txt')

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    FileNotFoundError: [Errno 2] No such file or directory: 'bad_file.txt'

    2.如果你要读取一个文件却没有权限,就得到一个权限错误permissionError:

    >>> fout = open('/etc/passwd', 'w')

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    PermissionError: [Errno 1] Operation not permitted: '/etc/passwd'

    3.如果你把一个目录错当做文件来打开,就会得到下面这种IsADirectoryError错误了:

    >>> find = open('/home')

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    IsADirectoryError: [Errno 21] Is a directory: '/home'

    我们可以用像是os.path.exists、os.path.isfile 等等这类的函数来避免上面这些错误,不过这就需要很长时间,

    还要检查很多代码(比如“IsADirectoryError: [Errno 21] Is a directory: '/home'”,这里的[Errno 21]就表明有至少21处地方有可能存在错误)。

    所以更好的办法是提前检查,用 try 语句来实现,这种语句就是用来处理异常情况的。其语法形式就跟 if...else 语句是差不多的:

    >>> try:

    ...    fout = open('bad_file.txt')

    ... except:

    ...    print('something went wrong!')

    ... 

    something went wrong!

    过程:

    Python 会先执行 try 后面的语句。如果运行正常,就会跳过 except 语句,然后继续运行。如果发生异常,就会跳出 try 语句,然后运行 except 语句中的代码。

    这种用 try 语句来处理异常的方法,就叫文件的异常捕获。上面的例子中,except 语句中的输出信息并没有实质性作用,仅仅是检查是否执行语句,而后的返回。

    结束。

  • 相关阅读:
    java Class.getResource和ClassLoader.getResource
    Ext Grid控件的配置与方法
    BLANK_IMAGE_URL
    js中变量和jsp中java代码中变量互相访问解决方案
    PL/SQL
    滴滴2021后端开发岗笔试:
    顺丰科技2021研发岗笔试:贪心算法应用
    2021顺丰科技研发笔试: 深度优先算法的应用
    动态规划算法轻松解决01背包,完全背包,多重背包问题
    寻找二叉树的最近公共祖先
  • 原文地址:https://www.cnblogs.com/liusingbon/p/13216626.html
Copyright © 2011-2022 走看看