DEV Community

Kajiru
Kajiru

Posted on

Getting Started with Python (Part 6): Understanding Errors and Exceptions

Understanding Errors and Exception Handling in Python

In this chapter, we’ll learn about errors and exception handling in Python.

By learning how to read error messages correctly, you’ll be able to find bugs much faster.

What Is an Error?

When you hear the word “error,” it often sounds scary or negative.

However, error messages actually contain many useful hints.

Below is a typical example of an error message.

By focusing on the following parts, you can quickly identify the file name, line number, and type of the error.

Traceback (most recent call last):
    File <file name>, line <line number>, in <module>
    The part where the error is believed to have occurred
ErrorType: error details (detected at line <line number>)
Enter fullscreen mode Exit fullscreen mode

Syntax Error

A SyntaxError is caused by a simple mistake in how the code is written.

In the example below:

  • The file name is main.py
  • The error occurred on line 1
  • The error type is SyntaxError

Using this information, you should check line 1 and look for a typo or missing symbol.

print("Hello, Python!!)

Traceback (most recent call last):
    File "/Users/xxx/main.py", line 1, in <module>
    print("Hello, Python!!)
          ^
SyntaxError: unterminated string literal (detected at line 1)
Enter fullscreen mode Exit fullscreen mode

Common SyntaxError patterns include:

Example Description
print("Hello, Python!!) Missing closing quote
print("Hello, Python!!" Missing closing parenthesis )
if a in range(10) Missing colon :

Name Error

A NameError occurs when you try to use a name that has not been defined in Python.

In the example below, you can quickly notice that prent looks suspicious.

The last line even suggests: “Did you mean print?”

prent("Hello, Python!!")  # 'prent' is not defined

Traceback (most recent call last):
    File "/Users/xxx/main.py", line 1, in <module>
    prent("Hello, Python!!")
    ^^^^^
NameError: name 'prent' is not defined. Did you mean: 'print'?
Enter fullscreen mode Exit fullscreen mode

Type Error

A TypeError is related to data types.

In the example below, an error occurs because a string ("Hello, ") is being concatenated with a number (100).

The error message tells us that strings and numbers cannot be concatenated directly.

print("Hello, " + 100)

Traceback (most recent call last):
    File "/Users/xxx/main.py", line 1, in <module>
    print("Hello, " + 100)
          ~~~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str
Enter fullscreen mode Exit fullscreen mode

In this case, you need to cast the number to a string.

print("Hello, " + str(100))
# Hello, 100
Enter fullscreen mode Exit fullscreen mode

Zero Division Error

A ZeroDivisionError occurs when you try to divide a number by zero.

(The result would be infinite, which is not allowed.)

In the example below, we intentionally divide 100 by 0.

print(100 / 0)

Traceback (most recent call last):
    File "/Users/xxx/main.py", line 1, in <module>
    print(100 / 0)
          ~~~~^~~
ZeroDivisionError: division by zero
Enter fullscreen mode Exit fullscreen mode

What Is Exception Handling?

Errors that are detected while a program is running are often called exceptions.

In most cases, when an error occurs, the program stops immediately.

Exception handling allows your program to catch specific errors and continue running instead of stopping.

The basic syntax looks like this:

try:
    # Code that may cause an error
except ErrorTypeYouWantToCatch:
    # Code to run when the error occurs (e.g., logging)
Enter fullscreen mode Exit fullscreen mode

In the example below, we intentionally trigger a ZeroDivisionError.

When the error occurs, the code inside the except block runs, and the program continues instead of stopping.

try:
    print(100 / 0)  # ZeroDivisionError...!!
except ZeroDivisionError:
    print("Please don't divide by zero...")
Enter fullscreen mode Exit fullscreen mode

Coming Up Next...

Thank you very much for reading!

The next chapter is titled “Using Conditional Statements”.

Stay tuned!

Top comments (0)