Python try-except statement - what's the exception handling?

Python string can't be added to integer and in that case, Python "returns" error.

x = 'abc'

y = x + 1

# TypeError: can only concatenate str (not "int") to str

Actually, Python raises (not returns) TypeError and stops the program. But we should not stop the program and handle the error properly. So Python has Exception Handling and the famous solution is to use try-except statement.

    x = 'abc'
    y = x + 1
except Exception:

a = 2 + 3

# Error!
# 5

Python executes try statement and...

  • if some errors happen, the except statement is executed. And Python calculates 2 + 3.
  • if no error happens, the except statement is ignored. And Python calculates 2 + 3.

If you don't use try-except statement, Python stops the program and may not handle the codes after the error happens.

No program is perfect. Generally speaking, the exception handling is critical for the whole system.


Powered by Markdown