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'
You can also try this code with Online Python Compiler
Run Code
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__']))
You can also try this code with Online Python Compiler
Run Code
To print a module that contains a dictionary of built-in exceptions, functions, and attributes, we can use the below command.
locals()['__builtins__']
You can also try this code with Online Python Compiler
Run Code
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
You can also try this code with Online Python Compiler
Run Code
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'
You can also try this code with Online Python Compiler
Run Code
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
You can also try this code with Online Python Compiler
Run Code
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'
You can also try this code with Online Python Compiler
Run Code
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'
You can also try this code with Online Python Compiler
Run Code
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
You can also try this code with Online Python Compiler
Run Code
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
You can also try this code with Online Python Compiler
Run Code
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
You can also try this code with Online Python Compiler
Run Code
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
You can also try this code with Online Python Compiler
Run Code
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 also try this code with Online Python Compiler
Run Code
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
Congratulations on making it this far.
In this blog, we understood Python's type-conversion and typecasting.
If you want to become proficient with Python programming, I suggest you take the Coding Ninjas Python Course, which will teach Python basics with Data Structures and Algorithms.
Recommended Readings:
Must Recommended Topic, Floor Division in Python
Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, etc. on Coding Ninjas Studio.
Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.
Cheers!