Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Java

    Spring Cloud Config Refresh Strategies

    Remote Job

    This Is Why Freelancing Is Not for Everyone | 5 Actual Lessons I Learned as a Freelancer

    Startups

    Strategic Approaches to Secure Capital for Your Tech Startup

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, August 27
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Python / How to customize exceptions in python
    Beginners

    How to customize exceptions in python

    Michael K.By Michael K.June 25, 2020Updated:May 26, 2024No Comments9 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    How to customize exceptions in python
    How to customize exceptions in python
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    How to customize exceptions in python. Cover
    How to customize exceptions in python

    In this tutorial we will look at the purpose of exception, types of exceptions, why it is important to include exceptions in your python programs and where in a python program you can include exceptions.

    In order to get practical understanding of how to use exceptions, we will build a python program to compute hash values of files based on md5 or sha256 algorithm.  We will implement custom  exceptions to deal with unexpected happenings such as empty input from users to prevent program from exiting abruptly.

    NB: Exception and Error in this context are interchangeable.

    Requirements:

    You need to have python version 3.7 on your local host to run this program. You can check here to find out to install python version 3.7 .

    What is an Exception?

    Exception occurs when something that is expected to happen does not happen or something that is not expected happens.  There are certain exceptions or errors that we can handle such as type errors and those we can’t easily handle such as out of memory error.

    For instance, let’s assume we have built a program in python which allows users to connect to blog.soshace.com to download articles or tutorials as shown below:

    import request
    resp = request("www.blog.soshace.com/how-to-build-a-python-program")
    print("resp")

    There is a possibility that the code above can end abruptly if there is no network connectivity or network latency is low.  In this case, we expected the user to connect and get the specified resource but because of connectivity problem, it can’t.

    In another instance, the code below can return a type error if a user enters any other value apart from an integer because the index method for the list data type accept only integers.

    users = ("Mike", "Nikita", "Kovavic", "Jokavic")   
    
    names = list(users)
    
    names["m"]

    If you run this code via the python interpreter, it shows the following as type error because list indices do not support strings.

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: list indices must be integers, not str

    We can handle errors like those above using exceptions: whether in-built or user-defined.

    Hierarchy of Exceptions

    There are various classes of exception. All of these classes, in-built such as TypeError, IndexError and custom or user-defined, inherit directly from the BaseException class or from sub-classes of the BaseException class such as the Exception class.

    However PSF recommends we inherit the Exception class instead of the Base Exception class. You can check here for a list of all exceptions in python.

    The BaseException class is the super class of all classes or kinds of exceptions in python.

    For instance, the code below technically shows how the InvalidAuth exception inherits from the Exception class.

     class InvalidAuth(Exception):  
        
        '' '' ''  Invalid authentication '' '' ''
    
    
        pass

    NB: Inheritance in python allows a class to inherit attributes or behaviours otherwise known as methods from another class.

    In this context, the InvalidAuth class becomes a subclass of Exception. So the Exception class is the super class of the InvalidAuth class.

    You can check here for detailed information on inheritance, classes and super class in python 3.

    Types of Exceptions:

    In python there are two main types of exceptions: in-built and user-defined exceptions.

    In-Built Exceptions:

    Some instances of in-built exceptions in python are as follows:

    KeyError:

    This type of error or exception usually shows up or occurs when the specified key is not present in a data structure such as a dictionary.

    Read More:  Flask vs. Django: Let's Choose the Right Framework for the Job

    The code below demonstrates how a program can terminate abruptly due to a key error if we decided to search for a non-existent key.

    users["Mike"]= "Accra"
    
    users["Nikita"]= "Petersburg"
    
    users["James"]= "London"  
    

     

    IndexError:

    This type of error occurs when index accessed is out of range. This error shows up when a program make use of a list or tuple data structure to store data.

    The code below demonstrates how a program can terminate abruptly due to an Index error.

    country = ['Russia', 'Germany', 'England', 'Japan', 'Korea']
    
    country[6]
    

     

    NameError:

    This type of error shows up if python interpreter tried to use a variable or a function but it has not been defined yet.   The code below shows how a name error occurs.

    input(''create a directory:    '')  
    os.mkdir(datastore)

     

    AttributeError: 

    Attribute error occurs when you try to access or contact an object’s attribute which does not yet exist.  The code below shows how attribute error occurs.

    class   FileName:  
    
    
             def  __init__(self, file, path):   
    
                self.file = file  
                self.path = path   
    
    
    
    f2.url

    Apart from these errors or exceptions, there are other errors such as Timeout, TooManyRedirects, and ConnectionError. You can check here for additional in-built exceptions.

    User-Defined Exceptions:

    These type of exceptions are usually implemented by developers who need specific type of exception to handle errors.

    Moreover, instead of also allowing in-built exception to output traceback when an exception is raised, we can customize it in our own way in this article. These type of exceptions inherit directly from the Exception class likewise in-built exceptions.

    For instance, we can create an exception such as the one below to handle or catch error such as when a user tells the program to search for a file but that file is not available on the system.

    class FileNotAvailable(Exception):  
       """ File is not available """
    
       pass    
    

    Why it is important to include exceptions in your program:

    The following shows why it is important to include exceptions in your python program to catch errors:

    1. It is unprofessional to deploy a program without a way to catch exceptions to production environment because it can dent a company’s reputation since the program can terminate abruptly or crash.
    2. The possibility of a company losing many customers due to the fact that it crashes often.
    3. Traceback printed by python can be a bit overwhelming.

    Where in a python program can you include exceptions:

    In this section, we will build a python tool to compute hash values of files. In addition, we will prevent the program from exiting abruptly by catching exceptions and customizing output to users.

    On the terminal create a file using the following command:

    touch cmd.py

    Open the cmd.py file with vim editor and paste the following import statements:

    import hashlib  
    
    import shutil 
    
    from os import platform
    
    import sys 
    

    Now save and close the cmd.py file using your file editor.

    The import statements are as follows:

    • import hashlib:  This imports hashlib module otherwise known as hashing library. hashlib comes with one-way hashing algorithm such as SHA-256 family algorithms made up of SHA-1 and SHA-2.
    • import os:  This os module provides functions to interact with filesystem.
    • import shutil: This module provides functions we can apply on a collection of files.
    • import sys:  This module manipulates the python runtime environment. 
    Read More:  Node.js Lesson 3: Node Package Manager

    Now copy and paste the following code to the cmd.py file as shown below:

    import hashlib
    import sys
    import os
    import shutil
    
    
    md5 = hashlib.md5()
    sha256 = hashlib.sha256()
    
    
    
    
    def make_dir():
      """ This function creates a directory within the program's directory """
    
    
      try:
          directory = input("create a directory:  ")
          os.mkdir(directory)
      except IOError:
         print("empty input not accepted. Create a directory")
      else:
         print("{} folder created successfully".format(directory)) 
         sys.exit()
    
    
    def create_files():
      """ This function creates a file inside the program's directory """
      try:
          file = input("create files:  ")
          f = open(file, 'a') 
    
      except IOError:
          print("empty input is not accepted. Create a file")
      else:
          print("{} created successfully".format(file))
          f.close()
          sys.exit()
    
    
    def  write_file():
      """ This function writes to a file inside the program's directory """
    
      file = input("choose file to write to: ")
      f = open(file, 'w', encoding='utf-8')
      text = input("write to file:    ")
      print("writing to {}".format(f))
      f.write(text)
      print("done!")
    
      f.close()
      sys.exit()
    
    
    
    
    def  hash_files():
    
      """ This function compute hash values of selected files """
    
      files_to_hash = list()
    
      user_files = input("choose files to compute hash values: ")
      hash_algo = input("Select hashing algorithm(MD5 or SHA-1):   ")
      files_to_hash = user_files
      if hash_algo == 'md5':
          for file in files_to_hash:
               md5.update(file.encode('utf-8'))
               hash_values = md5.digest()
               print("{}: {} ".format(file, hash_values))
    
     else:
    
         for file in files_to_hash:
              sha256.update(file.encode('utf-8'))
              hash_values = sha256.digest()
              print("{} : {}".format(file, hash_values))
    
    
    
    def display_menu():
     """ Displays functions to users on the terminal """
     print(""" 
    
           Methods Available:   
    
           1. Create files  
           2. Write to file
           3. Calculate files hash values 
           4. Create a directory 
           """)
    
    def run():
     """ Displays menu and allows user to choose a specific method """
    
    
     while True:
    
       display_menu()
       method = input("select a method by a number(pick other number to quit program):  ")
    
       if method == "1":
           print("calling the function to create files....")
           create_files()
    
       elif method == "2":
            print("you are about to write to a file......")
            write_file()
    
       elif method == "3":
            print("calling the hashing function.....")
            hash_files()
    
       elif method == "4":
           print("calling the make directory function.......")
           make_dir()
    
     
       else:
    
            print("exiting program")
            sys.exit()
    
    
    if __name__ == "__main__":
         run()
    
    
    

    Then save and close the cmd.py file using your file editor.

    The above code is made up of four functions respectively. These functions are described as follows:

    • create_files function:   This function allows a user to create files.
    • write_file function:  This function allows users to write to a file inside the program’s directory.  
    • hash_files function:  This function computes hash values of a file based on a user’s selected hashing algorithm.
    • make_dir function:  This function allows a user to create a directory inside the program’s root directory.

    In addition,  we decided to catch errors and customize it in our own way during a user’s input such when creating a file or a directory.

    On the terminal, execute the following command to run the program:

    python3 cmd.py  
    

    The program then prompts you to choose which function to run. You can choose to run any of the functions but initially you need to run the create_files and the write_file functions first.

    Then afterwards, you can call the hash_files function to compute hash values for files created.

    Conclusion:

    Although in this article, we made use of the try except syntax to handle both expected and unexpected happenings, we can also make use of the if else syntax in python to handle exceptions by controlling the flow of the program with regards to user’s input.

    So It is not always necessary to use the try except syntax to catch errors in the program. You can also deal with expected errors in a program using the if else syntax.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Michael K.

      Related Posts

      Flask Development Made Easy: A Comprehensive Guide to Test-Driven Development

      January 4, 2024

      Creating Our Own Chat GPT

      July 27, 2023

      The Ultimate Guide to Pip

      June 12, 2023
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      Node.js September 18, 2020

      Node.js Lesson 4: NPM Package Structure

      Hey everyone, this lesson is going to be all about the node package and its structure. We will understand what the package.json file actually is and its characteristics. We will learn what does those mighty properties inside package.json denotes and why they are important. Let’s start.

      Building Rest API With Django Using Django Rest Framework and Django Rest Auth

      January 30, 2021

      Interoperability between Ethereum, Binance Smart Chain, and other blockchain platforms using Node.js

      May 16, 2023

      Strategies for Identifying High-Quality LinkedIn Prospects by Niche

      November 24, 2024

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Startup Spotlight: Five Companies That Revolutionize Healthcare & Wellness

      Startups March 12, 2019

      What is Mentorship in Web Development | How to Find a Coding Mentor

      Tips July 24, 2019

      5. Уроки Node.js. Глобальные модули.

      Programming September 8, 2016

      Build Real-World React Native App #8 : implement Dark mode

      React December 29, 2020

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Flask

      Web development with Flask framework illustrated an address book project

      Programming

      Comprehension in Python

      Interview

      Behavioral Interview 101: How to Tackle the Toughest Questions | Sample Answers Included

      Most Popular

      Crafting Interactive User Interfaces Using JavaScript Techniques

      Programming

      Implementing Data Privacy Principles in Software Development

      Development

      Filtering, Sorting and Pagination – Advanced Filtering with React and Redux

      JavaScript
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.