Exception Handling in Python

Hello Friends,

Today in this article we are going to discuss about one of the most important point Exception Handling in Python

What is Exception Handling?

An exception is a Python object that represents an error. Python provides a way to handle the exception so that the code can be executed without any interruption. If we do not handle the exception, our program gives an error and the program breaks.

Common Exceptions

  1. ZeroDivisionError: Occurs when a number is divided by zero.
  2. NameError: It occurs when a name is not found. It may be local or global.
  3. FileNotFoundError: It occurs when any file is not found.
  4. IndentationError: If incorrect indentation is given.
  5. ModuleNotFoundError – It occurs when the module is not found

The problem without handling exceptions

Example – 1 ZeroDivisionError

numerator = 10
denominator = 0
print(numerator/denominator)
----------------------------------
Traceback (most recent call last):
  File "c:\Users\USER\TEST.py", line 4, in <module>
    print(numerator/denominator)
ZeroDivisionError: division by zero

Example – 2 NameError

Knowledge = input()
print(knowledge)
------------------------------------
Traceback (most recent call last):
  File "c:\Users\USER\TEST.py", line 2, in <module>
    print(knowledge)
NameError: name 'knowledge' is not defined. Did you mean: 'Knowledge'?

Example – 3 FileNotFoundError


file = open('myfile.txt')
lines = file.readline()
------------------------------------
Traceback (most recent call last):
  File "c:\Users\USER\TEST.py", line 2, in <module>
    file = open('myfile.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'

Example – 4 IndentetionError

fruits = ["apple", "banana", "cherry"]
for fruitnames in fruits:
print(fruitnames)
--------------------------------------------
  File "c:\Users\USER\TEST.py", line 3
    print(fruitnames)
    ^
IndentationError: expected an indented block after 'for' statement on line 2

Example – 5 ModuleNotFoundError

import flask
print("Hello world")
-------------------------------
Traceback (most recent call last):
  File "c:\Users\USER\TEST.py", line 1, in <module>
    import flask
ModuleNotFoundError: No module named 'flask'

Handling the exceptions

If we have some suspicious code that may raise an exception, we can defend our program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.

Example – 1 ZeroDivisionError

try :
  numerator = 10
  denominator = 0
  print(numerator/denominator)

except  ZeroDivisionError:
 print("Do not divide any number by zero")
-----------------------------------------------
Output
Do not divide any number by zero

Example – 2 NameError

try:
  Knowledge = input()
  print(knowledge)
except NameError:
 print("The name knowledge is not defined")
-------------------------------------------------
Output
The name knowledge is not defined

Example – 3 FileNotFoundError

try:
 file = open('myfile.txt')
 lines = file.readline()
except FileNotFoundError:
 print("The file is not found")
-------------------------------------------
Output
The file is not found

Example – 4 IndentationError

try: 
  fruits = ["apple", "banana", "cherry"]
  for fruitnames in fruits:
  print(fruitnames)
except IndentationError:
 print("Indentation error, please give the correct indentation")
-------------------------------------------------------------------
Output 
Indentation error, please give the correct indentation

Example – 5 ModuleNotFoundError

try:
  import flask
  print("Hello world")
except:
 print("please enter the correct module or install the module")
--------------------------------------------------------------------
Output
please enter the correct module or install the module

In next article – We will discuss about finally block

Thank you

Have a nice day 🙂

You may also like...

1 Response

  1. March 23, 2022

    […] you didn’t got chance to look my previous article on exception handling on Python – https://knowledge-junction.com/2022/03/19/exception-handling-in-python , please have a look […]

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: