Errors & Exceptions in Python

Errors & Exceptions

There are two major kinds of errors:

  1. Syntax Errors
  2. Exceptions

Syntax Errors

Syntax errors are parsing errors which occur when the code is not adhering to Python Syntax.


if True print("Hello")


SyntaxError: invalid syntax

When there is a syntax error, the program will not execute even if that part of code is not used.


def greet():  


SyntaxError: unexpected EOF while parsing


Even when a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.

Errors detected during execution are called exceptions.

Example Scenario

We wrote a program to download a Video over the Internet.

  • Internet is disconnected during the download
  • We do not have space left on the device to download the video

Example 1

Division Example

Input given by the user is not within expected values


def divide(a, b):  
    return  a / b  

divide(5, 0)


ZeroDivisionError: division by zero

Example 2

Input given by the user is not within expected values.


def divide(a, b):  
    return  a / b  

divide("5", "10")


TypeError: unsupported operand type(s) for /: ‘str’ and ‘str’

Example 3

Consider the following code, which is used to update the quantity of items in store.


class Store:  
    def __init__(self):  
        self.items = {  
        "milk" : 20, "bread" : 30, }  
    def add_item(self, name, quantity):  
       self.items[name] += quantity  
s = Store()  
s.add_item('biscuits', 10)


KeyError: ‘biscuits’

Working With Exceptions

What happens when your code runs into an exception during execution?

The application/program crashes.

End-User Applications

When you develop applications that are directly used by end-users, you need to handle different possible exceptions in your code so that the application will not crash.

Reusable Modules

When you develop modules that are used by other developers, you should raise exceptions for different scenarios so that other developers can handle them.

Raising Exceptions

When your code enters an unexpected state, raise an exception to communicate it.

Built-in Exceptions

Different exception classes which are raised in different scenarios.

You can use the built-in exception classes with raise keyword to raise an exception in the program.


We can pass message as argument .

raise ValueError("Unexpected Value!!")


ValueError:Unexpected Value!!

Handling Exceptions

Python provides a way to catch the exceptions that were raised so that they can be properly handled.

  • Exceptions can be handled with try-except block.
  • Whenever an exception occurs at some line in try block, the execution stops at that line and jumps to except block.
 # Write code that
 # might cause exceptions.
 # The code to be run when
 # there is an exception.

Example 1


    a = int(input())  
    b = int(input())  
    c = a/b
except ZeroDivisionError:  
    print("Denominator can't be 0")  
    print("Unhandled Exception")




Denominator can’t be 0

Handling Multiple Exceptions

We can write multiple exception blocks to handle different types of exceptions differently.


    # Write code that
    # might cause exceptions.
except Exception1:
    # The code to be run when
    # there is an exception.
except Exception2:
    # The code to be run when
    # there is an exception.

Related Posts

Python Program to Convert Integer into a Single Numeral

Single Digit Number Ram is given a positive integer N .He wishes to convert this integer into a single numeral. He does so by repeatedly adding the…

Python Program to Print Armstrong numbers between two intervals

Write a program to print all the Armstrong numbers in the given range A to B (including A and B). An N – digit number is an…

Python Program to Check if Given Input is a Letter, Digit or Special Character

Letter, Digit or Special Character You are given a character as input. Check if the given input is a Lowercase Letter or Uppercase Letter or Digit or…

Interleave Strings | Python Program to merge two strings by adding characters in alternating order

Interleave Strings Given two strings, write a program to merge the given two strings by adding characters in alternating order, starting with the first string. If a…

Python Program to Check if given colors are present in the color palate

Shekhar is an artist. He likes to draw and paint. He is now drawing a portrait of a city road which is in the black color and…

Python Program to Check the eligibility criteria for donor  

Python Comparison Operators An XYZ hospital has organised a blood donation camp. The eligibility criteria for donor was as follows  1) Age>=18  2) Weight >=50 kg  3)…

Leave a Reply

Your email address will not be published. Required fields are marked *