我如何使用函数捕获重复异常,而不是在以外编写相同的代码
目前,我有一个程序可以删除一些文件,复制新文件和重命名内容。我希望该程序继续正常工作,即使其中一个文件没有复制并引发例外。我正在使用以下代码处理异常:
try:
print("Removing old file...")
('W:/My Documents/test.exe')
print("Success!")
#Remove old file in W drive - EXCEPTION HANDLING
except WindowsError as e:
if e.winerror == 3 or e.winerror == 2:
print("Requested file does not exist.")
elif e.winerror == 5:
print("You do not have the required privilages to make changes to this file.")
print("One of the following solutions may work:")
print(" >The file might be open in another location, close the file and try again.")
print(" >Try to run the program as administrator.")
print(" >Change file security to allow read/write access to "+userName+".")
else:
print("Unexpected exception occured. Please copy the following exception and send it to xxx at xxx@abc")
print(e)
print("Program will try to continue")
except Exception as e:
print("Unexpected exception occured. Please copy the following exception and send it to xxx at xxx@abc")
print(e)
print("Program will try to continue")
问题是,我希望该程序单独尝试复制的5组文件集,并且所有这些文件都具有相同的例外处理。
我的问题是,我可以做一个能够处理这些重复例外的函数吗?或另一种不会使我的程序70%异常处理的方式。
Currently, I have a program that deletes a few files, copies new files, and renames stuff. I want the program to continue to work normally even if one of the files don't get copied and throw an exception. I am using following code to handle exceptions:
try:
print("Removing old file...")
('W:/My Documents/test.exe')
print("Success!")
#Remove old file in W drive - EXCEPTION HANDLING
except WindowsError as e:
if e.winerror == 3 or e.winerror == 2:
print("Requested file does not exist.")
elif e.winerror == 5:
print("You do not have the required privilages to make changes to this file.")
print("One of the following solutions may work:")
print(" >The file might be open in another location, close the file and try again.")
print(" >Try to run the program as administrator.")
print(" >Change file security to allow read/write access to "+userName+".")
else:
print("Unexpected exception occured. Please copy the following exception and send it to xxx at xxx@abc")
print(e)
print("Program will try to continue")
except Exception as e:
print("Unexpected exception occured. Please copy the following exception and send it to xxx at xxx@abc")
print(e)
print("Program will try to continue")
Problem is, there 5 different sets of files that I want the program to individually try to copy and all of them have the same exception handling.
My question is, can I make a function that handles these repetitive exceptions? Or another way that doesn't make my program 70% exception handling.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想了一些东西。显然,我可以将异常传递给功能并根据需要使用。我做了这样的事情:
尝试块是:
I figured something out. Apparently, I can pass the Exception to a function and use it however I want. I did something like this:
And try block being something like: