0% found this document useful (0 votes)
10 views3 pages

Python Built-in Exceptions Explained

The document outlines various built-in Python exceptions, providing a brief description and an example for each. Key exceptions include ZeroDivisionError, TypeError, ValueError, IndexError, KeyError, NameError, AttributeError, ImportError, IndentationError, FileNotFoundError, MemoryError, OverflowError, StopIteration, and RuntimeError. Each exception is raised under specific circumstances, such as dividing by zero or accessing an out-of-range index.

Uploaded by

nicipig995
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

Python Built-in Exceptions Explained

The document outlines various built-in Python exceptions, providing a brief description and an example for each. Key exceptions include ZeroDivisionError, TypeError, ValueError, IndexError, KeyError, NameError, AttributeError, ImportError, IndentationError, FileNotFoundError, MemoryError, OverflowError, StopIteration, and RuntimeError. Each exception is raised under specific circumstances, such as dividing by zero or accessing an out-of-range index.

Uploaded by

nicipig995
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Built-in Python Exceptions with

Examples
ZeroDivisionError
Raised when you divide a number by zero.

Example:

result = 10 / 0

TypeError
Raised when an operation is applied to an object of inappropriate type.

Example:

result = '2' + 3

ValueError
Raised when a function receives a correct type but inappropriate value.

Example:

num = int('abc')

IndexError
Raised when accessing an index out of range in a list or string.

Example:

lst = [1, 2, 3]
print(lst[5])

KeyError
Raised when a dictionary key is not found.

Example:

d = {'a': 1}
print(d['b'])
NameError
Raised when a variable is not defined.

Example:

print(xyz)

AttributeError
Raised when an invalid attribute is accessed on an object.

Example:

x = 10
[Link](5)

ImportError
Raised when an import statement fails.

Example:

import maths

IndentationError
Raised when indentation is incorrect. (Cannot be caught by try-except)

Example:

# def func():
# print('Hello')

FileNotFoundError
Raised when a file or directory is requested but doesn't exist.

Example:

f = open('[Link]')

MemoryError
Raised when an operation runs out of memory.

Example:

a = [1] * (10 ** 100)


OverflowError
Raised when a numerical calculation exceeds limits of the data type.

Example:

import math
[Link](1000)

StopIteration
Raised to signal the end of an iterator.

Example:

it = iter([1, 2])
next(it)
next(it)
next(it)

RuntimeError
Raised when an error is detected that doesn't fall in any category.

Example:

raise RuntimeError('Generic runtime error')

Common questions

Powered by AI

Python raises a ZeroDivisionError when a division by zero is attempted, as dividing a number by zero is mathematically undefined .

An IndexError is triggered when attempting to access an element in a list at an index that does not exist. For example, attempting to print the fifth element of a three-element list (lst[5] with lst = [1, 2, 3]) will raise an IndexError .

A KeyError is raised when attempting to access a dictionary key that is not found, indicating that the specified key exists but is not in the dictionary. In contrast, a NameError is raised when a variable is not defined at all in the current scope. For example, accessing a non-existent key 'b' in a dictionary {'a': 1} raises a KeyError, while trying to print an undefined variable 'xyz' raises a NameError .

Python raises an IndentationError when it encounters incorrect indentation, such as a misaligned block of code like a def statement without properly indented body. This error is a subclass of SyntaxError, meaning it occurs during the parsing stage before execution. Consequently, it cannot be caught with try-except blocks, which handle exceptions only at runtime .

A TypeError is raised when an operation is applied to an object of inappropriate type, such as trying to add a string and an integer (e.g., '2' + 3). This differs from a ValueError, which occurs when a function receives a value that is of the correct type but inappropriate, such as trying to convert a non-numeric string to an integer (e.g., int('abc')).

An ImportError is raised when an import statement fails because the module you are trying to import does not exist or is not accessible. For example, trying to import 'maths' instead of 'math' raises an ImportError. On the other hand, a RuntimeError is a generic error raised when an unspecified error occurs and does not fall into any other category; for instance, raising RuntimeError('Generic runtime error') explicitly. This type of error is more general and can cover a wide range of issues .

A ValueError is preferred over a TypeError when ensuring that the input type is valid but its value is inappropriate. This distinction is valuable in cases such as input sanitization, where a function may accept a string but the content should represent a valid number (e.g., 'abc' causing a ValueError when attempting int('abc')). TypeErrors are more general and apply when the type itself is incorrect, which might obfuscate the source of value-specific issues when not used distinctly .

Python signals the end of an iterator by raising a StopIteration exception. For example, after creating an iterator from a list (it = iter([1, 2])), using next(it) beyond the available elements, such as a third call in this case, results in a StopIteration exception, indicating that there are no more items to return .

An ImportError is raised when Python fails to locate or load a module, often because the module name is incorrect or the module is not installed. For example, writing 'import maths' instead of 'import math' leads to an ImportError. Correct module importing is crucial for code execution because it ensures that all dependencies are properly loaded and available for the script, which prevents runtime failures due to missing functionality .

An AttributeError occurs when an invalid attribute is accessed on an object, such as attempting to call .append on an integer, which does not support this method. For example, executing x = 10 followed by x.append(5) results in an AttributeError because integers do not have an append method .

You might also like