Errors and Exceptions

Hey there! Welcome back to the Python basics tutorial. Today I'm gonna tell you about all those errors you've been googling recently if you've been tinkering with Python yourself.

Errors

When you make a mistake in your code, such as missing a quote or parenthesis, or forgetting to add a def before defining your function, you get errors. Errors usually crash your program. When you face an error, your code stops executing and displays an error message, along with a traceback, pointing to the file and line where the error happened. Fire up the python console:

>>> Harry Potter
  File "<stdin>", line 1, in <module>
    Harry Potter
               ^
SyntaxError: invalid syntax
>>>

Let's take a look at the first line: File "<stdin>", line 1, in <module> This shows the name of the file, in this case, stdin which means standard input, then you can see the exact line and <module> (which shows the place such as inside a function).

After that, there's a ^ pointing where the error happened. The very last line is the most important one: It displays the name of the error. In our case, we executed a bunch of invalid code, so it caused a SyntaxError. If you try to divide something by 0:

>>> 21/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 

If you try to convert a non-number string to an integer:

>>> int('Armando Salazar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Armando Salazar'
>>>

And there are a lot more, you'll discover them as you learn.

Exceptions

Errors usually show up before your code executes, such as when there's a SyntaxError, your code will crash before it runs. An exception is an error that is encountered after the code starts running such as when an invalid function is called but not when it's defined. This may seem a little confusing, so I'll demonstrate with an example:

>>> def wrong():
...     htuvhruht4uovht4uh4ivuhn4
...
>>> wrong()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in wrong
NameError: name 'htuvhruht4uovht4uh4ivuhn4' is not defined
>>> 

See? When we defined the function, there were no errors. But when we executed the function, errors popped up.

All errors are exceptions, but not all exceptions are errors.

Looks interesting. Can I deliberately cause errors?

Sure you can. While programming, we call "causing errors" raising an error. You can raise exceptions and errors with the raise keyword:

>>> raise Exception('You messed up big time.')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: You messed up big time.
>>> 

Or use a ValueError, NameError, or a SyntaxError.

>>> raise SyntaxError('You forgot a quote for the last time.')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
SyntaxError: You forgot a quote for the last time.
>>>

But Errors and Exceptions annoy me. How do I stop them?

Suppressing errors is usually not a good idea. However, you may want to display a nice helpful message instead of an intimidating error. For that, you put your code in a try/catch block, which is pretty similar to an if/else statement.

try:
    a = 5 / 0
except ZeroDivisionError:
    print('Oh no! You can\'t divide by zero!')

First we try to run the code, and if we face a ZeroDivisionError, display a polite message instead of spewing out errors. We can use except without specifying any errors, but that will catch every single error which can lead to unexpected results later on. Suppressing errors and doing something else is called catching errors. There's also a finally keyword which runs the code regardless of whether there were errors or not.

try:
    print abcd
    print('This code will not run')
    
except SyntaxError:
    print('This code is gonna run when there\'s a SyntaxError')

finally:
    print('This code doesn\'t give a damn if there are errors or not.')

Before I end this chapter, here's a handy list for future reference: https://docs.python.org/3/library/exceptions.html You'll find all of the exceptions in Python over there. Oh, and a sneak peek, you've almost finished half of the beginner stuff, so from next part, we'll be doing some fun stuff.

Last updated