Fundamentals 8 min read

Master Python’s Most Common Exceptions: When and Why They Occur

This article explains why Python programs raise common built‑in exceptions, illustrates each with clear code examples, and shows practical techniques for catching, raising, and debugging these errors to write more robust code.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python’s Most Common Exceptions: When and Why They Occur

When writing Python programs, exceptions frequently appear due to careless mistakes or unavoidable runtime conditions such as inconsistent web page structures in crawlers. Capturing these exceptions prevents programs from terminating unexpectedly.

Python provides many built‑in exceptions that anticipate typical programming errors, offering precise feedback to help locate bugs. Below is a concise mind‑map of all built‑in exceptions and their trigger conditions:

1. SyntaxError

Raised when Python syntax is invalid, such as missing colons or mismatched quotes.

In [1]: While True print('1')
  File "<ipython-input-1>", line 1
    While True print('1')
          ^
SyntaxError: invalid syntax

2. TypeError

Occurs when an operation is applied to an object of inappropriate type, e.g., adding an integer to a string.

In [8]: a = [1,2]; b = [2,3]
In [9]: a - b
---------------------------------------------------------------------------
TypeError: unsupported operand type(s) for -: 'list' and 'list'

3. IndexError

Triggered when a sequence index is out of range.

In [16]: m = [1,2,3]
In [17]: m[4]
---------------------------------------------------------------------------
IndexError: list index out of range

4. KeyError

Raised when accessing a non‑existent key in a dictionary.

In [18]: dict_ = {'1':'yi','2':'er'}
In [19]: dict_['3']
---------------------------------------------------------------------------
KeyError: '3'

5. ValueError

Occurs when a function receives an argument of correct type but inappropriate value.

In [22]: n = [1,2,3]
In [23]: n.index(4)
---------------------------------------------------------------------------
ValueError: 4 is not in list

6. AttributeError

Raised when an attribute reference or assignment fails because the object lacks that attribute.

In [25]: dict_ = {'1':'yi','2':'er'}
In [26]: dict_.index('1')
---------------------------------------------------------------------------
AttributeError: 'dict' object has no attribute 'index'

7. NameError

Occurs when a variable name is not found in the local or global scope.

In [27]: print(list_)
---------------------------------------------------------------------------
NameError: name 'list_' is not defined

8. FileNotFoundError

Raised when attempting to open a file that does not exist.

In [29]: fb = open('./list','r')
---------------------------------------------------------------------------
FileNotFoundError: [Errno 2] No such file or directory: './list'

9. StopIteration

Signals that an iterator has no more items.

In [30]: list1 = [1,2]
In [31]: list2 = iter(list1)
In [33]: next(list2)  # 1
In [34]: next(list2)  # 2
In [35]: next(list2)
---------------------------------------------------------------------------
StopIteration

10. AssertionError

Raised when an assert statement fails.

In [45]: list3 = [1,2]
In [46]: assert len(list3) > 2
---------------------------------------------------------------------------
AssertionError

Beyond these common exceptions, Python also allows developers to define custom exception classes.

Python offers several robust mechanisms for handling exceptions, including:

try ... except

try ... except ... finally

try ... except ... else

raise to explicitly raise an exception

try ... raise ... except to trigger an exception

assert statements

traceback module for detailed error inspection

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DebuggingprogrammingCode ExamplesExceptions
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.