Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax Error
3.
Logical Error(Exception)
4.
Built-in Exceptions
4.1.
Examples of Built-in Exceptions
4.1.1.
ZeroDivisionError Exception
4.1.2.
ValueError Exception
4.1.3.
AssertionError Exception
4.1.4.
AttributeError Exception
4.1.5.
ModuleNotFoundError Exception
4.1.6.
OverflowError Exception
4.1.7.
IndexError Exception
4.1.8.
KeyError Exception
4.1.9.
KeyboardInterrupt Exception
4.1.10.
NameError Exception
5.
Frequently Asked Questions
5.1.
What is the difference between exceptions and errors?
5.2.
Is there any way to handle exceptions in Python?
5.3.
How to find a list of all exceptions in Python?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Exception & Errors in Python

Author APURV RATHORE
0 upvote
gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

While working with any programming language, one may inevitably make some mistakes while writing a program that may lead to errors when trying to run the program. As soon as the Python program encounters an unhandled error, it immediately terminates and informs the user about the error. 

An error can be classified into two types of errors:

  1. Logical errors (exception)
  2. Syntax error

Also See, Divmod in Python, Swapcase in Python

Syntax Error

Syntax errors, also called parsing error, is caused by a lack of proper structure of the Python code. This error occurs when the user makes a mistake following the syntax rule. 

Example 1:

for i in range(5)
    print(1)

 

Output:

    for i in range(5)
                     ^
SyntaxError: invalid syntax

In the above piece of code, we can see that the colon is absent after the for a loop. The arrow indicates at which place the parser encountered the error. Hence it throws a syntax error. 

Example 2:

for i in range(100):
    if i=2:
        print(i)

 

Output:

    if i=2:
        ^
SyntaxError: invalid syntax

In the above example, we can see that in the if statement, there is only one equal to sign instead of two which isn’t a valid syntax, hence it throws a syntax error. 

You can also read about the Multilevel Inheritance in Python.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

 

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

 

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"

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)


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


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))


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


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


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 


Output:

    pass
KeyboardInterrupt

NameError Exception

The AssertionError exception is raised when an assert exception fails.
Example:

def fun():
    print(var)
fun()


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

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!

Previous article
Exception Handling in Python
Next article
Raising an Exception
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass