Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Exceptions in Python: Different Types of Exceptions and How to

Handle them in Python


Whenever you write larger pieces of code and build more complex applications, exceptions in
Python will be commonplace. They can get annoying when one is unable to resolve them.

When do errors occur?

 Giving the wrong input


 A module/library/resource is unreachable
 Exceeding the memory or time
 Any syntax error made by the programmer

Different Exceptions in Python


An exception is defined as a condition in a program that interrupts the flow of the program and
stops the execution of the code. Python provides an amazing way to handle these exceptions
such that the code runs without any errors and interruptions.

Exceptions can either belong to the in-built errors/exceptions or have custom exceptions. Some
of the common in-built exceptions are as follows:

1. ZeroDivisionError
2. NameError
3. IndentationError
4. IOError
5. EOFError

Creating a test exception in Python


Let’s look at some examples of how exceptions look in the Python Interpreter. Let’s look at the
output of the code given below.

1a = int(input("Enter numerator: "))


2b = int(input("Enter denominator: "))
3print("a/b results in : ")
4print(a/b)

The output when the numerator is an integer and the denominator is given as 0 is shown below.

Enter numerator: 2
Enter denominator: 0
a/b results in :
Traceback (most recent call last):
  File "C:/Users/Hp/Desktop/test.py", line 4, in <module>
    print(a/b)
ZeroDivisionError: division by zero

Avoid Exceptions with Try..Except..


In order to avoid the errors coming up and stop the flow of the program, we make use of the try-
except statements. The whole code logic is put inside the try block and the except block handles
the cases where an exception/error occurs.

The syntax of the same is mentioned below:

try:   
    #block of code    
 
except <Name of Exception>:   
    #block of code   
 
#Rest of the code

Handling ZeroDivisionError Exceptions in Python


Lets’ look at the code we mentioned earlier showing ZeroDivisionError with the help of try-
except block. Look at the code mentioned below.

1try:
2    a = int(input("Enter numerator: "))
3    b = int(input("Enter denominator: "))
4    print(a/b)
5except ZeroDivisionError:
    print("Denominator is zero")
6

The output of this code for the same inputs as before is shown below.

Enter numerator: 2
Enter denominator: 0
Denominator is zero

You might also like