如果我尝试执行此代码,为什么不调用sys.excepthook
函数?
import sys;
def MyExcepthook(ex_cls, ex, tb):
print("Oops! There's an Error.\n");
a=open("./ERR.txt","w"); #Fixed as suggested by unutbu BUT the problem is the same!
a.write("Oops! There's an Error.\n");
a.close();
sys.excepthook = MyExcepthook;
def main():
print(1/0);
if (__name__=="__main__"):
main();
输出:
Traceback (most recent call last):
File "C:\Users\Path\to\my\python\file.py", line 13, in <module>
main();
File "C:\Users\Path\to\my\python\file.py", line 10, in main
print(1/0);
ZeroDivisionError: division by zero
预期输出(print
):
Oops! There's an Error.
应创建一个新文件(Err.txt
)(open
)
print
函数未显示文本且未创建文件,因为未调用sys.excepthook
函数 - 为什么?
- &gt;编辑 我的问题是由idle-python 3.4中的一个错误引起的,因为现在我试图通过解释器python(命令行)运行代码并且它可以工作!如果不在idle-python 3.4中警告这个错误,这使得我的问题毫无用处。对不起,谢谢你的帮助!
[解决方案] 如果有人有同样的问题=&gt;尝试通过命令行运行您的代码!而不是来自IDE。
答案 0 :(得分:3)
您的自定义异常错误本身不得引发异常:
a=open("./ERR.txt") # opens the file in read mode
应该是
a=open("./ERR.txt", 'w') # open the file in write mode.
当自定义excepthook引发异常时,您应该看到
之类的东西Oops! There's an Error.
Error in sys.excepthook:
...
IOError: [Errno 2] No such file or directory: './ERR.txt'
Original exception was:
...
ZeroDivisionError: integer division or modulo by zero
PS。不要忘记删除所有那些不必要的分号!
import sys
def my_excepthook(ex_cls, ex, tb):
msg = "Oops! There's an Error.\n"
print(msg)
with open("./ERR.txt", 'w') as a:
a.write(msg)
sys.excepthook = my_excepthook
def main():
print(1/0)
if __name__=="__main__":
main()