Logical Error(Exception)
These errors occur at the runtime after the syntax test has been passed. They occur because of a logical error by the user; hence they are called logical errors or exceptions.
For example, we may try to divide a number by zero, which is an invalid operation (ZeroDivisionError), or we may attempt to import a library that does not exist (ModuleNotFoundError).
Python produces an exception object if these types of runtime issues occur. It outputs a traceback to that problem and some data about why that issue happened if it is not handled appropriately.
Example:
>>> import lib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'lib'
Check out this article - String slicing in Python and Convert String to List Python.
Built-in Exceptions
There are several built-in exceptions in Python. All the exceptions in Python must be instances of a class that derives from the BaseException class. Two exception classes that are not related by subclassing are never equivalent.
Using the built-in local() method, we can see all of the built-in exceptions, as seen below.
print(dir(locals()['__builtins__']))
To print a module that contains a dictionary of built-in exceptions, functions, and attributes, we can use the below command.
locals()['__builtins__']
Examples of Built-in Exceptions
There are many built-in exceptions present in Python. Some of them, along with their examples, are mentioned below.
ZeroDivisionError Exception
The AssertionError exception is raised when an assert exception fails.
Example:
a = 1/0

You can also try this code with Online Python Compiler
Run Code
Output:
ZeroDivisionError: integer division or modulo by zero
ValueError Exception
The ValueError exception is raised when a function receives an argument that has the correct type but an invalid value.
Example:
a = 1/0

You can also try this code with Online Python Compiler
Run Code
Output:
num = int("str")
ValueError: invalid literal for int() with base 10: 'str'
AssertionError Exception
The AssertionError exception is raised when an assert exception fails.
Example:
assert 1<0, "Condition not met"

You can also try this code with Online Python Compiler
Run Code
Output:
assert 1<0, "Condition not met"
AssertionError: Condition not met
AttributeError Exception
When an attribute reference or assignment fails, such as when a non-existent attribute is referenced, an AttributeError is thrown.
Example:
class Human:
pass
person = Human()
print(person.tail)

You can also try this code with Online Python Compiler
Run Code
Output:
print(person.tail)
AttributeError: 'Human' object has no attribute 'tail'
ModuleNotFoundError Exception
The ModuleNotFoundError exception is raised when the user tries to import a library that does not exist.
Example:
import module

You can also try this code with Online Python Compiler
Run Code
Output:
import module
ModuleNotFoundError: No module named 'module'
OverflowError Exception
The OverflowError exception is raised when the limits of the platform’s support for float are reached.
Example:
import math
print (math.exp(100000))

You can also try this code with Online Python Compiler
Run Code
Output:
print (math.exp(100000))
OverflowError: math range error
IndexError Exception
The IndexError exception is raised when a sequence is indexed with a number that is out of range.
Example:
arr = [5,6,7]
arr[5]=1

You can also try this code with Online Python Compiler
Run Code
Output:
arr[5]=1
IndexError: list assignment index out of range
KeyError Exception
The KeyError exception is raised when there was an issue retrieving the key used.
Example:
d = {}
d[1]=d[1]+1

You can also try this code with Online Python Compiler
Run Code
Output:
d[1]=d[1]+1
KeyError: 1
KeyboardInterrupt Exception
The KeyboardInterrupt exception is raised when the user uses the interrupt key to halt the program.
Example:
while 1:
pass

You can also try this code with Online Python Compiler
Run Code
Output:
pass
KeyboardInterrupt
NameError Exception
The AssertionError exception is raised when an assert exception fails.
Example:
def fun():
print(var)
fun()

You can also try this code with Online Python Compiler
Run Code
Output:
print(var)
NameError: name 'var' is not defined
You can practice by yourself with the help of online python compiler.
Frequently Asked Questions
What is the difference between exceptions and errors?
The problems in the program due to which the program is not able to complete its execution are called errors. In contrast, exceptions are raised due to some internal event that obstructs the normal flow of the execution.
Is there any way to handle exceptions in Python?
Exceptions can be manually handled by the user using try-except statements.
How to find a list of all exceptions in Python?
The built-in exceptions in Python can be viewed by using “locals()['__builtins__']” function. It returns a dictionary of built-in exceptions, attributes, and functions in Python.
Conclusion
Exception and error handling in Python ensures robust, user-friendly programs. Errors disrupt execution, while exceptions allow graceful handling using constructs like try-except. Effective management prevents crashes, improves debugging, and enhances code reliability. Custom exceptions provide clarity for specific cases.
Recommended Readings:
Must Recommended Topic, Floor Division in Python