What is the use of raise function!?

Is raise function used to raise errors when in reality there aren’t any!?

Making sure your code isn’t doing things you don’t want it to can help to catch bugs. It’s sometimes useful for a function to raise an Exception if you give it something it doesn’t expect. For example:

def time_string(hours, minutes):
    if not isinstance(hours, int):
        raise TypeError("hours is not an int")
    if not isinstance(minutes, int):
        raise TypeError("minutes is not an int")
    if not 1 <= hours <= 12:
        raise ValueError("hours should be between 1 and 12.")
    if not 0 <= minutes <= 59:
        raise ValueError("minutes should be between 0 and 59.")
    return f"{hours}:{minutes}"

>>> time_string(0.001, None)
Traceback (most recent call last):
  ...
TypeError: hours is not an int

>>> time_string(17, "foo")
Traceback (most recent call last):
  ...
TypeError: minutes is not an int

>>> time_string(17, 100)
Traceback (most recent call last):
  ...
ValueError: hours should be between 1 and 12.

>>> time_string(5, -1)
Traceback (most recent call last):
  ...
ValueError: minutes should be between 0 and 59.

>>> time_string(5, 15)
'5:15'

If you had instead left out those if- and raise-statements, the function “succeeds” every single time, but the results aren’t useful:

def time_string_2(hours, minutes):
    return f"{hours}:{minutes}"

>>> time_string_2(0.001, None)
'0.001:None'
>>> time_string_2(17, "foo")
'17:foo'
>>> time_string_2(17, 100)
'17:100'
>>> time_string_2(5, -1)
'5:-1'
>>> time_string_2(5, 15)
'5:15'

If you have a big program doing lots of things and you accidentally call time_string_2 with the wrong types of arguments, then your script might, say, send an email with a bogus time in it, and you might not even realizing anything is wrong! With those raise statements added, if something like that isn’t working, you find out immediately.

That’s not to say you should clutter every other line of your code with raise statements, but it’s a tool that can be useful sometimes.

1 Like

@sweeneyde thank you, my guy. It was bugging me for a while​:blush::smiley: