Python Forum
How to exit after a try exception?
Thread Rating:
  • 3 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to exit after a try exception?
#11
When you call the main() function in if __name__ == "__main__": block do it as a sys.exit() callback. This will give the main() return status to sys.exit() which prints it to stderr. You may have to put many sys.exit() calls in the code to exit if needed. It is not necessary. Organise your program logic to not need sys.exit() in the middle of the code.

Instead of:

def main():
    num = 52234

    try:
        n = int(input("Enter a number up to 100: "))
    except:
        print("Error!\n {}".format(sys.exc_info()[0])) 

    if num == 0: # or again try/except
        sys.exit("Zero diivision. Program terminated!")
    else:
        result = num / n
        print(result)

if __name__ == __main__:
    main()
You can do:

def main():
    num = 52234

    n = int(input("Enter a number up to 100: "))
    result = num / n
    print(result)

if __name__ == "__main__":
    sys.exit(main())
    
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#12
(Mar-05-2017, 08:30 AM)wavic Wrote: When you call the main() function in if __name__ == "__main__": block do it as a sys.exit() callback. This will give the main() return status to sys.exit() which prints it to stderr. You may have to put many sys.exit() calls in the code to exit if needed. It is not necessary. Organise your program logic to not need sys.exit() in the middle of the code.

Instead of:
.... snip ....

I'll study the sample code that you posted as I don't quite understand it all yet.
Some Googling will be necessary.
Thanks much for taking the time to help out.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python difference between sys.exit and exit() mg24 1 1,821 Nov-12-2022, 01:37 PM
Last Post: deanhystad
  name of exception for exit() Skaperen 2 2,395 May-24-2019, 07:07 PM
Last Post: Skaperen
  During handling of the above exception, another exception occurred Skaperen 7 26,864 Dec-21-2018, 10:58 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020