From the course: Certified Entry-Level Python Programmer (PCEP-30-02) Cert Prep

Unlock the full course today

Join today to access over 24,500 courses taught by industry experts.

Using exceptions and try-except

Using exceptions and try-except

- [Instructor] Let's see exceptions in action. For example, a pretty common scenario is to ask a number from the user. For that, we use input and we say enter a number. And we know that when we execute this, we always receive int, the number variable, a string. So we typically wrap this input in an int function that will actually convert that into an integer. So if I execute this, it's enter a number, I enter a number, everything works. But if I enter a letter or text, then this is actually an exception in action. What's the exception here? ValueError. So you will see in the terminal in the console the exception name here in ValueError. So can we intercept this error before my app crashes? We can do that. How? For that we're going to use a new code block that we haven't seen so far that is called try. So we are going to try to execute this code. So try will be followed by the code block that we want to try. And then we're…

Contents