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
7
  • The maximum port number you can give is 65535. Detailed Explanation Here Commented Jun 16, 2022 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 Commented Jun 16, 2022 at 15:04
  • 1
    How about if x > 65535: ... then do something else? Commented Jun 16, 2022 at 15:21
  • 1
    Then you are executing different code than you have shown here. Commented Jun 16, 2022 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. Commented Jun 16, 2022 at 16:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.