Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Handling Python Errors

00:00 There are three major kinds of errors in Python: syntax errors, which are errors caused by writing invalid Python code; exceptions, or runtime errors, which are errors that occur when code is executed; and semantic errors, not errors in the traditional sense of crashing your program, but logical errors that prevent your program from running as expected.

00:21 Let’s see a few of these live in the REPL. Syntax errors happen immediately, even in the REPL. Say you try to write a conditional missing a colon, for instance, if x less than 9.

00:35 SyntaxError, expected colon. It doesn’t matter that x is actually undefined at this point. The error is raised as soon as Python tries to read the line.

00:44 Or try a malformed list. my_list = 1, 2, 3 closing bracket.

00:52 SyntaxError, unmatched bracket. In both examples, Python helpfully points out where on the line you went wrong, as well. As for an exception, back to that first conditional, try this.

01:05 if x less than 9, colon, print(x).

01:11 Now you get a NameError: name 'x' is not defined. Nothing wrong with the syntax, just trying to access a non-existent variable. Something we’ve all done at times.

01:21 What about a semantic error? Think back to our countdown example from discussing while loops. count = 3.

01:30 while count greater than 0,

01:33 print(count).

01:34 And if you run this while forgetting to decrease count by 1, what happens?

01:42 Okay, yeah, that’s what’s known as an infinite loop. If I hadn’t used Control-C to stop it with that KeyboardInterrupt, it would have run forever.

01:51 And if you’re following along really closely at home, I’m sorry about that. In fact, exceptions are common, especially in live apps dealing with unpredictable user inputs.

02:02 Philosophically, you can choose to try to prevent them from happening or set up ways to handle them when they occur. If you want to learn more about how that works, check out Handling or Preventing Errors in Python: LBYL vs EAFP.

02:16 And you’ll have to watch to find out what those stand for. Next, let’s look at some coding tools that’ll hopefully help you prevent these errors before they happen.

Become a Member to join the conversation.