为什么sys.excepthook无效?
为什么我执行这段代码时,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
这个函数没有被调用——这是为什么呢?
-->编辑
我遇到的问题是由于 idle-python 3.4 的一个bug,因为我现在尝试通过命令行的python解释器运行代码,结果是可以正常工作的!这让我的问题变得没意义了,如果不是为了提醒大家注意idle-python 3.4的这个bug,我感到抱歉,并感谢大家的帮助!
[解决方案] 如果有人和我有同样的问题 => 尝试通过命令行运行你的代码!而不是通过IDE。
1 个回答
5
你自己写的异常处理函数不能再抛出异常:
a=open("./ERR.txt") # opens the file in read mode
应该是
a=open("./ERR.txt", 'w') # open the file in write mode.
当自定义的异常处理函数抛出异常时,你应该看到类似这样的内容
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
附言:别忘了删掉那些多余的分号哦!
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()