Write a Python try-except block that handles a specific exception, and show what happens without one.
A try block holds the code that might fail, and the except clause names the type of error you want to handle. When the error happens, the except clause runs instead of the rest of the try block.
def parse_int(text):
try:
return int(text)
except ValueError:
return None
print(parse_int('42')) # 42
print(parse_int('hello')) # None
# Without a handler the error travels up to the caller.
try:
int('hello')
except ValueError as err:
print('ValueError:', err)
When int raises a ValueError inside the try block, the except clause runs and the function gives back None. When nothing goes wrong, the except clause is skipped completely and the value from the try block is returned.
The as err part attaches the error object to a name, and that is what lets you read its message. Without it you can still catch the error, but you cannot look at it, and all you get is the traceback.
The important point to remember is that an error which nobody catches does not stop quietly. It travels up the call stack, and if nothing higher up handles it either, Python prints the traceback and the program ends. So catching an error is a decision to deal with it in this function instead of passing it to the caller.
One more detail matters. Keep the try block as small as you can, and put only the statement that can really fail inside it. Everything else in that block is skipped when the error happens, including work that had nothing to do with the failure.