Hi, I need to write an expection that if a string is null, then fire this exception. How to write this?
Eg. str = get_str()
if get_str() returns None or nothing. It should raise an exception.
Hi, I need to write an expection that if a string is null, then fire this exception. How to write this?
Eg. str = get_str()
if get_str() returns None or nothing. It should raise an exception.
There is no such thing as "nothing" in Python. There is either something, or there is not.
if str is None:
raise SomeException()
returning None (which is the same as not returning anything explicitly) isn't an exception by itself. If it should be an exception, get_str() should raise this exception, and it's up to you to decide what the correct reason and therefore correct exception is. It may be ValueError, TypeError or something custom. E.g.
def get_str():
x = some_complex_computation()
if x is None:
raise ValueError("because it's wrong!!")
return x
However, often, None will be a valid return value. Either check it explicitly once you get the return value as Ignacio points out, or just use "duck typing": assume you get a string back and let python fail if it isn't. E.g.
str = get_str()
if 'foo' in str:
print "Looks okay!"
if str is None, python will fail at the 'in' expression with a TypeError exception.