If you literally want to raise an exception only on the empty string, you'll need to do that manually:
try:
user_input = input() # raw_input in Python 2.x
if not user_input:
raise ValueError('empty string')
except ValueError as e:
print(e)
But that "integer input" part of the comment makes me think what you really want is to raise an exception on anything other than an integer, including but not limited to the empty string.
If so, open up your interactive interpreter and see what happens when you type things like int('2')
, int('abc')
, int('')
, etc., and the answer should be pretty obvious.
But then how do you distinguish an empty string from something different? Simple: Just do the user_input = input()
before the try
, and check whether user_input
is empty within the except
. (You put if
statements inside except
handlers all the time in real code, e.g., to distinguish an OSError
with an EINTR
errno
from one with a different errno
.)