handling 2 exceptions at once - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: handling 2 exceptions at once (/thread-27915.html) |
handling 2 exceptions at once - Skaperen - Jun-26-2020 i have mishandling of a case of 2 exceptions at the same time. if each happens one at a time, they are handled OK. but if a second exception happens, i get the trace backs. i want to just gave them both handled. here is the output i dob't want to get: here is the end of the code where it happens:if __name__ == '__main__': from sys import argv,stderr,stdin,stdout,version_info cmdpath = argv.pop(0) if argv and argv[0][:2]=='--': if '--help' in argv: help() if '--version' in argv: version() try: result=main(cmdpath,argv) except BrokenPipeError: exit(141) except KeyboardInterrupt: print(flush=True) exit(98) if result is None or result is True: exit(0) elif result is False: exit(1) exit(int(float(result)))i can provide the entire code if you need it (213 lines. 6153 bytes) RE: handling 2 exceptions at once - bowlofred - Jun-27-2020 You could call your exit() from a finally: block. That will execute before the default handler gets invoked. If your intent is to actually exit the program, that will succeed.Something like this to show the idea? import sys while True: try: print(3/0) except: print("I just caught one exception...still going...") int("x") print("I won't get here...") finally: # without this finally block, will end in traceback print("had some problems. Exiting") sys.exit(5)And inside the finally block (if you're at least 3.6 I think), then you can examine sys.exc_info(). If it's all None, then the other exception handlers finished. If it's populated, then all the exceptions were not handled. RE: handling 2 exceptions at once - Yoriz - Jun-27-2020 (Jun-26-2020, 11:02 PM)Skaperen Wrote: i have mishandling of a case of 2 exceptions at the same time.They are not happening at the same time the second one occurs in the handling of the first. try: raise KeyboardInterrupt except KeyboardInterrupt: raise BrokenPipeError put a try/except block inside the handlertry: raise KeyboardInterrupt except KeyboardInterrupt: try: raise BrokenPipeError except BrokenPipeError: print('caught BrokenPipeError')
|