|
注意Raise的用法:
- #-*- encoding:UTF-8 -*-
- import os
- def mkPath(sourcePath, destPath):
- # ent1-ls = sourcePath.split('/')[1:]
- # ent2-ls = destPath.split('/')[1:]
- # if os.path.exists(destPath):
- # return True
- # else:
- try:
- os.makedirs(destPath)
- except Exception as err:
- print('mkPath Error:', str(Exception), str(err)) # print(repr(Exception), srepr(err))
- # raise # ??如加入这句,则系统抛出错误停止运行。就是说重新抛出错误,上面已经打印的情况下,
- # 重新向python解释器默认错误处理器抛出错误。
- finally:
- print('After deal with except, I am doing.') # 这句在重抛错误之前打印。
- print(destPath + '已建立路径,如无报错则建立成功。') # except 处理完毕之后,系统继续执行程序。
- if __name__ == '__main__':
- sourcePath = 'c:\\nonono'
- destPath = 'n:\\nonono'
- mkPath(sourcePath, destPath)
- print('Up ok .')
复制代码
嵌套的异常:
- #-*- encoding:UTF-8 -*-
- import os
- def mkPath(sourcePath, destPath):
- # ent1-ls = sourcePath.split('/')[1:]
- # ent2-ls = destPath.split('/')[1:]
- # if os.path.exists(destPath):
- # return True
- # else:
- try:
- try:
- os.makedirs(destPath)
- except IOError as err:
- print('mkPath Error:', repr(IOError), str(err)) # print(repr(IOError), repr(err)) repr(err)显示效果不好。
- raise # ??如加入这句,则系统抛出错误停止运行。就是说重新抛出错误,上面已经打印的情况下,
- # 重新向python解释器默认错误处理器抛出错误。注意只抛一层,在外层就接住了。
- finally:
- print('After deal with inner except, I am doing.') # 这句在重抛错误之前打印。
- print(destPath + '已建立路径,如无报错则建立成功。') # except 处理完毕之后,系统继续执行程序。
- except Exception as err:
- print('Im outer exception dealing.')
- raise # 这个raise名字就叫做抛,抛毛的抛。
- if __name__ == '__main__':
- sourcePath = 'c:\\nonono'
- destPath = 'n:\\nonono'
- mkPath(sourcePath, destPath)
- print('Up ok .')
复制代码
控制台显示如下:
- mkPath Error: <class 'OSError'> [WinError 3] 系统找不到指定的路径。: 'n:\\'
- After deal with inner except, I am doing.
- Im outer exception dealing.
- Traceback (most recent call last):
- File "<stdin>", line 4, in <module>
- File "<stdin>", line 9, in mkPath
- File "C:\Python36\lib\os.py", line 210, in makedirs
- makedirs(head, mode, exist_ok)
- File "C:\Python36\lib\os.py", line 220, in makedirs
- mkdir(name, mode)
- FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'n:\\'
复制代码
如果把第二个raise去掉,则输出如下:
- mkPath Error: <class 'OSError'> [WinError 3] 系统找不到指定的路径。: 'n:\\'
- After deal with inner except, I am doing.
- Im outer exception dealing.
- Up ok .
复制代码
注意可以通过Exception的派生类捕获特定的异常。 |
|