Why is sys.excepthook not working?

Why is the function not being called sys.excepthook

if I try to execute this code?

import sys;
def MyExcepthook(ex_cls, ex, tb):

    print("Oops! There an Error.\n");

    a=open("./ERR.txt","w"); #Fixed as suggested by unutbu BUT the problem is the same!
    a.write("Oops! There an Error.\n");
    a.close();

sys.excepthook = MyExcepthook;

def main():
    print(1/0);

if (__name__=="__main__"):
    main();

      

Output:

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

      

Expected Output (on print

):

Oops! There an Error.

      

and a new file ( Err.txt

) should be created ( open

)

The function print

does not display text and the file is not created because the function is sys.excepthook

not called - why?

-> EDIT My problem is caused by a bug in idle-python 3.4 because now I was trying to run the code with the python interpreter (command line) and it works! this makes my question useless without warning about this error in idle-python 3.4. Sorry and thanks for your help!

[SOLUTION] if anyone has my problem => Try running code on command line! not from the IDE.

+3


source to share


1 answer


Your custom excepthook shouldn't throw an exception itself:

a=open("./ERR.txt")   # opens the file in read mode

      

it should be

a=open("./ERR.txt", 'w')  # open the file in write mode.

      




When a custom excepthook throws an exception, you should see something like

Oops! There 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. Don't forget to remove any extra semicolons!

import sys
def my_excepthook(ex_cls, ex, tb):
    msg = "Oops! There 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()

      

+3


source







All Articles