views:

53

answers:

2

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.

+3  A: 

There is no such thing as "nothing" in Python. There is either something, or there is not.

if str is None:
  raise SomeException()
Ignacio Vazquez-Abrams
+1 for philosophy :)
Space_C0wb0y
Could we use some kind of built-in exceptions?
Absolutely. But it may make sense to use a custom exception.
Ignacio Vazquez-Abrams
@user469652: which one would you like: http://docs.python.org/library/exceptions.html#bltin-exceptions `ValueError` looks fine to me.
eumiro
Depending on the situation, `TypeError` might also be appropriate.
Deniz Dogan
None is Python's nothing, yet None is something; therefore, in Python, nothing is something.
Glenn Maynard
A: 

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.

Ivo van der Wijk