-3

I didn't understand why we should use try and except in our code. I mean when the code is wrong, the system always returns some error telling us which part cannot pass coding. From my understanding, try and except also throw some error to us when the code goes wrong. So, could anyone tell me why we should use try and except?

Root
  • 97
  • 1
  • 12
  • read [this](https://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python). It provides an explanation of `try-except-else`, but still provides an explanation of why exception handling is used. [Here](https://jeffknupp.com/blog/2013/02/06/write-cleaner-python-use-exceptions/) is a blog post about exception handling, and finally the official Python tutorial has a good section on it here: https://docs.python.org/3/tutorial/errors.html – idjaw Jun 27 '17 at 02:42
  • Imagine you've written some code that takes some input. If that input is not what it is expected to be, it makes sense, instead of throwing an error, to sometimes “catch” that exception, and instead execute some code that compensates for the error. – perfect5th Jun 27 '17 at 02:43
  • `try` / `excepts` is not about errors. It is about exceptions. Things that did not happen as they might be expected to happen. You don't really want to end the program on any minor problem that might be easy to handle with a few lines of code. – Klaus D. Jun 27 '17 at 02:43

1 Answers1

1

One example of using try/except could be as simple as detecting whether a value casts to another value to act upon the result of the cast properly.

try:
    x = int(unknown_value)
    # Execute more logic on x now that it is known to be safe
except ValueError:
    # Execute different logic now that x is known not to be a numeric value

This is a very basic example, but could be a use case to answer you question.

AgnosticDev
  • 1,843
  • 2
  • 20
  • 36