0

I am taking user input for port number and using that to start a python webserver. If I type in 20000000 as the port number then I get an OverflowError exception (as expected) however; is there any way I can handle this exception within the code so as it will just return an invalid port response whenever this error is spun up ?

from http.server import BaseHTTPRequestHandler, HTTPServer
import time

hostName = "localhost"   #self-explanatory - local host

#unit test - error message when ports are over 65,535

valid = False
while not valid: #loop until the user enters a valid int
    try:
        x = int(input('Welcome to EZ Python Webserver \nEnter the port number for your webserver i.e. 8000'))  #Enter port you wish to use
        valid = True                         #if this point is reached, x is a valid int
    except ValueError:
        print('Please only input digits')    #Error message for not inputting digits
    except OverflowError as err:
        print('Overflowed after ', err)
    else:
        serverPort = x
  • The maximum port number you can give is **65535**. [Detailed Explanation Here](https://stackoverflow.com/questions/113224/what-is-the-largest-tcp-ip-network-port-number-allowable-for-ipv4) – Ghanteyyy Jun 16 '22 at 15:00
  • Yes but my issue is when a user inputs a random number like 200000000 I want it to throw an error rather than exit out of the .py file with an overflow error – Andy Thompson Jun 16 '22 at 15:04
  • 1
    How about `if x > 65535: ... then do something else`? – mkrieger1 Jun 16 '22 at 15:21
  • Also you shouldn't get an OverflowError if the user enters 200000000. Python can handle arbitrarily large integers perfectly. – mkrieger1 Jun 16 '22 at 15:23
  • tried that already - still throws up the overflow error even though it prints the conditional statement – Andy Thompson Jun 16 '22 at 15:23
  • 1
    Then you are executing different code than you have shown here. – mkrieger1 Jun 16 '22 at 15:24
  • 1
    This code as posted will not throw and error for large numbers because it never tries to do anything with the port number. – bfris Jun 16 '22 at 16:20

0 Answers0