Python在发生异常的情况下继续执行 [英] Python Continue with execution in case of exception

查看:84
本文介绍了Python在发生异常的情况下继续执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管存在异常,我仍试图继续执行我的代码.只需打印异常并继续执行代码即可.

I am trying to continue with my code eventhough exception is present. Just print the exception and continue with code.

下面是示例:

def mkdir(path):
        mypath = "./customers/"+path
        print(mypath)
        try:
            os.makedirs(mypath)
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(mypath):
                pass

if __name__ == '__main__':
    item = 'dev'
    mkdir(item)
    print("Done")

但是它永远不会打印完成.

But It never prints Done.

控制台输出

./customers/dev
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-45-3ce58775d916> in mkdir(path)
      4         try:
----> 5             os.makedirs(mypath)
      6         except OSError as exc:

/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py in makedirs(name, mode, exist_ok)
    220     try:
--> 221         mkdir(name, mode)
    222     except OSError:

FileExistsError: [Errno 17] File exists: './customers/dev'

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-45-3ce58775d916> in <module>
     10 if __name__ == '__main__':
     11     item = 'dev'
---> 12     mkdir(item)
     13     print("Done")

<ipython-input-45-3ce58775d916> in mkdir(path)
      5             os.makedirs(mypath)
      6         except OSError as exc:
----> 7             if exc.errno == errno.EEXIST and os.path.isdir(mypath):
      8                 pass
      9 

NameError: name 'errno' is not defined

请帮助

推荐答案

需要导入errno模块.

Need to import errno module.

errno模块定义了许多符号错误代码

The errno module defines a number of symbolic error codes

这篇关于Python在发生异常的情况下继续执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆