Python Errors and Built-in Exceptions
Python Errors
While writing code, we can make some mistakes that lead to errors when running the code.
A Python program is terminated as soon as it encounters an unhandled error. These errors can be classified into two types:
- Syntax Errors
- Logical Errors (Exceptions)
Python Syntax Errors
Syntax error(also called parsing error) is caused by not following the Python language's proper structure (syntax).
Let us see the following example:
if x > 0
Output
File "<interactive input>", line 1
if x > 0
^
SyntaxError: invalid syntax
As we can see above, an arrow indicates where the parser ran into the syntax error.
The error was caused by the missing of the colon :
in the if statement.
Python Logical Errors (Exceptions)
Errors that happen at runtime (after passing the syntax check) are called exceptions or logical errors.
For example, they occur when we try to divide a number by zero (ZeroDivisionError
), try to open a file(for reading) that does not exist (FileNotFoundError
), or try to import a module that does not exist (ImportError
).
Whenever a runtime error happens, Python creates an exception object. If not handled correctly, it prints a traceback to that error and some details about why it occurs.
Let us in the following example, how Python treats these errors:
>>> open("non_existing.txt")
FileNotFoundError Traceback (most recent call last)
----> 1 open("non_existing.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'non_existing.txt'
>>> 5/0
ZeroDivisionError Traceback (most recent call last)
----> 1 5/0
ZeroDivisionError: division by zero
Python Built-in Exceptions
There are many built-in exceptions in Python that are raised when corresponding errors occur.
To view all the built-in exceptions, we can use the built-in function locals()
as foolows:
print(dir(locals()['__builtins__']))
Output
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'dreload', 'enumerate', 'eval', 'exec', 'execfile', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'runfile', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
The locals()['__builtins__']
returns a module of built-in exceptions, attributes, and functions. The dir()
function allows us to list these attributes as strings.
In the following table, some of the standard built-in exceptions in Python with the error that cause them.
Exception | Cause of Error |
---|---|
AssertionError |
Raised when an assert statement fails. |
AttributeError |
Raised when reference or attribute assignment fails. |
EOFError |
Raised when the input() function hits end-of-file condition. |
FloatingPointError |
Raised when a floating-point operation fails. |
GeneratorExit |
Raised when a generator's close() method is called. |
ImportError |
Raised when the imported module is not found. |
IndexError |
Raised when the index of a sequence is out of range. |
KeyError |
Raised when a key is not found in a dictionary. |
KeyboardInterrupt |
Raised when the user hits the interrupt key (Ctrl+C or Delete ). |
MemoryError |
Raised when an operation runs out of memory. |
NameError |
Raised when a variable is not found in the local or global scope. |
NotImplementedError |
Raised by abstract methods. |
OSError |
Raised when system operation causes a system-related error. |
OverflowError |
Raised when the result of an arithmetic operation is too large to be represented. |
ReferenceError |
Raised when a weak reference proxy is used to access a garbage collected referent. |
RuntimeError |
Raised when an error does not fall under any other category. |
StopIteration |
Raised by next() function to indicate that there is no further item to be returned by the iterator. |
SyntaxError |
Raised by the parser when a syntax error is encountered. |
IdentationError |
Raised when there is incorrect indentation. |
TabError |
Raised when indentation consists of inconsistent tabs and spaces. |
SytemError |
Raised when interpreter detects an internal error. |
SystemExit |
Raised by sys.exit() function. |
TypeError |
Raised when a function or operation is applied to an object of the incorrect type. |
UnboundLocalError |
Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. |
UnicodeError |
Raised when a Unicode-related or decoding error occurs. |
UnicodeEncodeError |
Raised when a Unicode-related error occurs during encoding. |
UnicodeDecodeError |
Raised when a Unicode-related error occurs during decoding. |
UnicodeTranslateError |
Raised when a Unicode-related error occurs during translating. |
ValueError |
Raised when a function gets an argument of correct type but improper value. |
ZeroDivisionError |
Raised when the second operand of division or modulo operation is zero. |