Python Built-in Exceptions Explained
Python Built-in Exceptions Explained
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 .