Explore
ProGrad Programs
Placement Prep
TCS Codevita
Webinars
About Us

Edit
Reply




Edit

Exception Handling In Python | FACE Prep

Published on 09 Mar 2020

In this article, we will be discussing Exception Handling in Python 3. But before that, let us understand about an exception and some of the common exceptions that can occur in Python programs.


Exception In Python


An exception is an error that occurs during the run time of your program. For instance, consider you have written a below-given program to divide two numbers.

#program to divide two numbers
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
res = a / b
print(int(res))
print("FACE Prep")

For the input values 10 and 5, the above code works fine and prints 2 as the output. But, if the user inputs 10 and 0, the above code produces an exception saying,

Traceback (most recent call last):
File "main.py", line 3, in <module>
res = a / b
ZeroDivisionError: division by zero

In general, a number cannot be divided by zero. Since the user inputs zero as the second input value during the run time, the Python interpreter has produced an exception.

Whenever an exception occurs in the program, the Python interpreter stops its execution and prevents your program from getting crashed. Below are some of the common Python exceptions.


Python Exceptions


Some of the exceptions that can occur in a Python program are listed below.

  • IOError (Input Output Error) This error occurs if a file cannot be opened
  • ImportError This error occurs if Python cannot find a module
  • KeyboardInterrupt - This error is raised when the user hits the interrupt key (normally Ctrl+C or Delete)
  • ZeroDivisionError: This error occurs when a number is divided by zero
  • NameError: This error occurs when the name of a local or a global variable is not found
  • EOFError: It occurs when the end of a file is reached, and yet operations are being performed

Next, let us see what is the need for handling exceptions in Python.


Why Do We Need To Handle Exceptions?


If we do not handle an exception, the Python interpreter terminates the entire execution of the program. So, handling exceptions is very important for the other part of the program to execute without any disruption.

Whenever a code produces any exceptions, using exception handling blocks we can handle those exceptions. Below are the blocks to handle Python exceptions.


Python Exception Handling Blocks


a) try-except


In Python, we mainly use two blocks 'try' block followed by 'except' block to handle exceptions. Any Python program that is suspicious to raise exceptions should be written inside the 'try' block. And the 'except' block should be written with the code that has to be executed when an exception occurs.

In the above-given example code, the first three lines of the code are suspicious to raise exceptions. So, they need to be written inside the 'try' block.

try:
  a = int(input("Enter the first number: "))
  b = int(input("Enter the second number: "))
  res = a / b
except:
  print("Cannot divide a number by zero")

If the user enters the second input as zero, then the statement inside the 'except' block gets printed.

Input from the user:
10
0
Output:
Cannot divide a number by zero

Assume a case where the user inputs 5 as the second input value. In this case, the exception will not be raised in the program. Suppose if you need to execute some statements when there is no exception in the code, you can use 'else' block to execute those statements.


b) else


'else' block should be written with the code that has to be executed if no exception occurs in the code. So, we can write the print statements inside the 'else' block to print the results if there is no exception in the code as shown below.

try:
  a = int(input("Enter the first number: "))
  b = int(input("Enter the second number: "))
  res = a / b
except:
  print("Cannot divide a number by zero")
else:
  print(int(res))
  print("FACE Prep")
Input from the user:
10
5
Output:
2
FACE Prep

We need some statements to be executed irrespective of the occurrence of exceptions. Such statements can be executed by writing them inside a 'finally' block.


c) finally


The statements written inside the 'finally' block will be executed regardless of the exception status. Statements that perform an operation like closing a file can be written inside the 'finally' block as closing the file has to be done irrespective of exception occurrence.

try:
  a = int(input("Enter the first number: "))
  b = int(input("Enter the second number: "))
  res = a / b
except:
  print("Cannot divide a number by zero")
else:
  print(int(res))
  print("FACE Prep")
finally:
  print("Program to divide two numbers")
Input from the user:
10
0
Output:
Cannot divide a number by zero
Program to divide two numbers


Python Exception Handling FAQs


1) What is Exception in Python?

An exception is an error that occurs during the run time of your program.


2) What is Exception Handling in Python?

Python Exception Handling allows us to handle exceptions ( errors occur during the run time of a program) using the blocks try, except, else, finally.


3) How to catch Exception in Python?

In Python, an exception can be caught using the block ‘except’. The statements written inside this block will be executed if there is an exception in the code.


4) List out keywords used in Exception Handling in Python.

Keywords used to handle Python exceptions are try, except, else, finally.

If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in
Explore 'python'
Articles