Try / Except

Hi there,

Just starting out on Python, and have a couple of questions about the Try / Except statements.

Firstly, on my introduction to Try / Except, I wrote this;

def raises_value_error():
  try:
    raise ValueError
  except ValueError:
    print("You raised a ValueError!")

raises_value_error()

which seemed to work perfectly. However checking on the hints of the lesson, I see that they have wrote this instead;

def raises_value_error():
    raise ValueError
  
try:
    raises_value_error()
except ValueError:
    print("You raised a ValueError!")

Both of them work fine, but I don’t understand why their try and except statements are outside of the function indentations. Surely the way to build in those statements would be within the function? Can anyone explain why they have written it outside of the indents, or why I am doing it wrong?

Also, with the ability to give custom messages for any possible error, surely it is best practice to put everything you write in a file, within try statements as this would give you much more power in seeing whats gone wrong within your code? Or am I mis-understanding the potential of the try statement?

2 Likes

As it is for demonstration purposes, the subtleties of their example over yours is hard to notice.

As for why it is useful, sometimes there are situations where your code might try to go “out of bounds” but you don’t want it to crash if it does. For example: with some sort of loop, you try to access a list item where there is no index. Sometimes you can write conditionals to preempt these crashes, other times a try/except is the best way to keep things working.

I’m sure there are better examples than the one I just mentioned, but know that try/except is quite useful.

3 Likes