I'm just starting to programming, so I may not know the proper way to ask a question. Please understand this first.
In the book or on the Internet, it is said that exceptions are used to prevent the interpreter from stopping and crashing. But I can't tell the difference between when I must use an exception and when I must use an if-else. For example, let's say I have the following code:
a, b, c = 1, 2, 3
def join_strings(arr):
global a, b, c
a = arr[0]
b = arr[1]
c = arr[2] # IndexError: list index out of range
return arr[0] + arr[1] + arr[2]
join_strings(["A", "B"])
Of course, I can prevent crashing by using an exception. But if I need rollback i.e. a, b, c should be 1, 2, 3 respectively if fails, I will have to write code to find out why the exception occurs, check how far the state has progressed, and rollback it again. How is this different from checking the value of len(arr) rather like below? For example, what is the proper way?
# option 1: Just wrap it with try/catch
# Should check status and needs rollback if I need
def join_strings(arr):
try:
a = arr[0]
b = arr[1]
c = arr[2] # IndexError: list index out of range
except:
...
# option 2: do some check to avoid rollback process
def join_strings(arr):
if len(arr) < 3:
raise IndexError("list index out of range")
# option 3: same with option 2 but return somevalue
def join_strings(arr):
if len(arr) < 3:
print('error. you should check this')
return -1
else:
...
What is the proper way to use exception? Programming books explain what exceptions are, but I don't understand exactly why they are needed or how to use them.
I googled and found Joel's Blog. But I'm a beginner, so I don't know what it means, and I don't even know a suitable search term on Google. Can you give me a more understandable use case or rule of thumb?