When programmers refer to raise an error it means to catch an unexpected behaviour what something goes wrong. As a simple example in Python:
int('a')
>>
----> 1 int('a')
ValueError: invalid literal for int() with base 10: 'a'
This makes sense, cause intuitively, you won't expect any program to cast a string value like a
into a integer unless explicitly defined somewhere. And there are benefits to this, if the error was never raised, an unexpected behaviour might occur that breaks the program flow without anybody knowing.
A IRL example would be for example your car, if you are low on gas, you are notified through an indicator on your dashboard display, that is like a form of a notification raised to let you know you are low on gas that allows you to make an informed decision. Similarly, when you program, good errors are raised to inform you that something is not working accordingly and allows you to make an informed decision on how to manage or mitigate it.
As an example:
def multiply(a, b):
try:
return int(a) + int(b)
except ValueError as e:
print('{}, one or both inputs cannot be converted'.format(e))
multiply('1', 'a')
>> invalid literal for int() with base 10: 'a', one or both inputs cannot be converted
Because there was a ValueError
raised, I am able to catch it and inform the user that one of the inputs has failed. If nothing was raised, it would be similar as driving your car not knowing when the gas is finished leading you to confusion.
How are these errors raised?
If I have a function to check whether a value is in the range of 10 I can do it like:
def in_range_10(n):
for i in range(1,11):
if i == n:
return i
raise IndexError(n)
Every value from 1 to 10 will return the value itself because it is in range, but if the value goes above 10, an error is throw with raise IndexError
and the value itself.
in_range_10(11)
>> ...
3 if i == n:
4 return i
----> 5 raise IndexError(n)
IndexError: 11