Exceptions can be raised both by the Python interpreter and by the user. Also in Python, built-in exceptions aid in the detection of frequent faults in a program. Because we must obey the syntactic rules when writing in any programming language, a minor typing error can result in an error. The Python interpreter usually reports it immediately, along with the reason. In this post, we’ll look at what errors and exceptions are, how they are utilized, and what are the different types of errors in Python.
Python Errors
When we write a program, we can make mistakes that cause errors when we run it. When a Python program meets an unhandled error, it terminates. A Python object that reflects an error is known as an exception. The different types of errors in Python can be broadly classified as below:
- Errors in syntax (Syntax Errors)
- Errors in logic (Logical Errors) (Exceptions)
Python Syntax Errors
This is the most common and fundamental error scenario. The most typical cause of an error in a Python program is when a certain statement is not used correctly. A syntax error or parsing error is a type of error like this. The Python interpreter reports it promptly, generally along with the explanation.
Example 1
print 'Good Morning Everyone!'
Output
File "", line 1
print 'Good Morning Everyone!'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('Good Morning Everyone!')?
The print statement is a built-in function in Python 3.x and requires parentheses. Because the above statement violates this usage, a syntax error is displayed. An arrow in the example indicates where the parser encountered the syntax problem.
Similarly, if you don’t include a colon (:) at the conclusion of the if condition, you’ll get a SyntaxError:
Example 2
a = 10
if a < 20
print('Value of a less than 20')
Output
File "", line 2
if a < 20
^
SyntaxError: invalid syntax
Python Logical Errors (Exceptions)
However, even if a program does not have any syntax errors, it will frequently produce an error when run. This type of problem is known as a runtime error or an exception.
Other types of errors in Python – Exceptions or logical errors are errors that occur at runtime (after passing the syntax test). When an exception occurs, the program halts execution, and the subsequent code is not performed. As a result, run-time failures that cannot be handled by the Python script constitute an exception.
For example, they occur when we attempt to open (read) a file that does not exist (FileNotFoundError), divide an integer by zero (ZeroDivisionError), or import a module that does not exist (ImportError). Python generates an exception object if these types of runtime issues occur. If the error is not handled appropriately, it prints a traceback to the error as well as some information about why the issue happened.
Example 1
a = 10
b = 0
print('Result of Division: ', (a/b))
Output
Traceback (most recent call last):
File "", line 3, in
ZeroDivisionError: division by zero
As we can see in the output, we received ZeroDivisionError despite the fact that the syntax of our Python code was perfectly proper, because the problem, or should we say the exception, was caused during code execution. Python returns a very descriptive error message to help us understand the origin point and reason for the problem so that we may correct our code more easily.
Example 2
open('my_file.txt')
Output
Traceback (most recent call last):
File "", line 1, in
FileNotFoundError: [Errno 2] No such file or directory: 'my_file.txt'
Python Built-in Exceptions
Python has a number of built-in exceptions, such as the well-known errors SyntaxError, NameError, and TypeError. These Python Exceptions are thrown by standard library routines or by the interpreter itself. They are built-in, which implies they are present in the source code at all times.
When an error occurs, Python raises a number of built-in exceptions. These built-in exceptions can be examined with the local() built-in functions, which is as follows:
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', '__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', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', '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', 'quit',
'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
The locals()[‘__builtins__’] returns a module containing built-in exceptions, functions, and attributes. We can use dir to list these characteristics as strings.
Python’s built-in exceptions are organized hierarchically, which means that they derive from common base classes. As a result, they are nearly identical in terms of attribute and method scope. The table below lists the built-in exception Types and the most typical conditions in which they occur.
Exception | Cause of Error |
AssertionError | When an assert statement fails, an error is raised. |
ArithmeticError | It specifies when an error in numerical calculations occurs. |
AttributeError | When attribute assignment or reference fails, this exception is raised. |
EOFError | When the input() method encounters a “end of file” circumstance, it throws an error (EOF) |
FloatingPointError | When a floating-point calculation fails, this error is generated. |
GeneratorExit | When the close() method of a generator is called, this variable is raised. |
ImportError | When the imported module cannot be found, this exception is thrown. |
IndexError | When the index of a sequence is out of range, this value is raised. |
KeyError | When a key is not found in a dictionary, this error is raised. |
KeyboardInterrupt | When the user pushes Ctrl+C, Ctrl+Z, or Delete, this exception is thrown. |
MemoryError | When a program runs out of memory, an error is generated. |
NameError | When a variable is not discovered in the local or global scope, this exception is raised. |
NotImplementedError | Raised through abstract methods. |
OSError | When a system operation results in a system-related error, this flag is raised. |
OverflowError | When the result of a numerical calculation is too huge, an error is raised. |
ReferenceError | This Is an Exception When a weak reference object does not exist, an error is raised. |
RuntimeError | When an error does not fit into any of the other categories, it is raised. |
StopIteration | Raised by the next() function to indicate that the iterator has no more items to return. |
SyntaxError | When a syntax problem occurs, the parser raises this exception. |
IndentationError | It raises an error when the indentation is incorrect. |
TabError | It raises an error when the indentation consists of tabs or spaces. |
SystemError | It is triggered when a system error occurs. |
SystemExit | The sys.exit() function raised this exception. |
TypeError | When a function or operation is applied to an object of the wrong type, this exception is raised. |
UnboundLocalError | When a reference to a local variable in a function or method is made but no value is bound to that variable, an exception is raised. |
UnicodeError | When a Unicode-related encoding or decoding problem occurs, this flag is raised. |
UnicodeEncodeError | When a Unicode-related problem occurs during encoding, this flag is raised. |
UnicodeDecodeError | When a Unicode-related error occurs while decoding, this flag is raised. |
UnicodeTranslateError | It defines an error. When there is an issue with a Unicode translation, this flag is raised. |
ValueError | When there is an incorrect value in a specified data type, this exception is raised. |
ZeroDivisionError | When the second operator in a division is zero, an error is raised. |
In Python, we may even define our own exceptions if necessary. In Python, we may manage these built-in and user-defined exceptions with try, except, and finally statements.
Frequently Asked Questions
Q1. What are the three types of errors in Python?
Errors and exceptions can be quite frustrating at times, making coding appear to be a futile endeavor. There are three types of errors in python programming. They are as follows:
- Syntax Errors – Syntax or parsing errors are errors produced by not following the right structure (syntax) of the language. Syntax errors are the most fundamental sort of error. They occur when the Python parser cannot interpret a line of code.
- Runtime Errors – Run time errors occur when Python understands what to do with a piece of code but is unable to execute the action. Your code may be syntactically correct, but if Python encounters something it cannot handle during runtime, it will throw an exception.
- Logical Errors – A logic error occurs when a program is correctly designed by obeying all of the syntactical rules, but an error is made in arranging the statements in the proper order. The most difficult to correct are logical flaws. They arise when the software continues to operate without crashing but produces an inaccurate result.
Q2. What are errors in the Python program?
When we write a program, we can make mistakes that cause errors when we run it. When a Python program meets an unhandled error, it terminates. A Python object that reflects an error is known as an exception.
Q3. What are logical errors in Python?
Exceptions or logical errors are types of errors in Python that occur at runtime (after passing the syntax test). When an exception occurs, the program halts execution, and the subsequent code is not performed. As a result, run-time failures that cannot be handled by the Python script constitute an exception. The most difficult to correct are logical flaws. They arise when the software continues to operate without crashing but produces an inaccurate result.
For example, they occur when we attempt to open (read) a file that does not exist (FileNotFoundError), divide an integer by zero (ZeroDivisionError), or import a module that does not exist (ImportError).
Leave a Reply