• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Types of Exceptions in Python with Examples

  • January 4, 2023
  • CODE OF GEEKS
  • 0
In this Tutorial -:
  • Types of Exceptions in Python
    • 1. Exception in Python
    • 2. ArithmeticError Exception in Python
    • 3. Assertion Error Exception in Python
    • 4. Type Error Exception in Python
    • 5. Value Error Exception in Python
    • 6. Key Error Exception in Python
    • 7. Name Error Exception in Python
    • 8. Index Error Exception in Python
Types of Exceptions in Python with Examples
Types of Exceptions in Python with Examples
Types of Exceptions in Python with Examples

Pre–requisite: Exception Handling in Python

Exception in Python is considered as the runtime error that can be handled by a developer using various techniques of exception handling in Python.

Exceptions can be suppressed or handled using try, except, and finally block in Python. This mechanism of handling runtime errors is termed as Exception Handling in Python.

This tutorial is all about types of Exceptions in Python.

Types of Exceptions in Python

1. Exception in Python

This class covers all type of exception. All exceptions are the subclasses of this class.

Use of Exception class is helpful in all those situations where you are not sure which type of exception you should handle in your program.

Example code

def find_divisor(n1, n2):
    try:
        res = n1/n2
        print('Result is : ', res)
    except Exception as e:
        print('Some Exception encountered.')
        print('Details are: ', e)

# calling the method
find_divisor(20, 0)

O/P

Some Exception encountered.
Details are: division by zero

In the above code, instead of handling the specific exception, we have used common Exception class that will allow us to handle any exception that may occur in the program.



2. ArithmeticError Exception in Python

Use of ArithmeticError exception class is helpful in all those situations where you are sure that your program may throw an arithmetic error.

Example code

def find_divisor(n1, n2):
    try:
        res = n1/n2
        print('Result is : ', res)
    except ArithmeticError as a:
        print('Arithmetic Exception encountered.')
        print('Details are: ', a)

# calling the method
find_divisor(20, 0)

O/P

Arithmetic Exception encountered.
Details are: division by zero

In the above code, we have used ArithmeticError class that will allow us to handle any arithmetic error in the code.



3. Assertion Error Exception in Python

Use of AssertionError exception class is helpful in handling all the errors raised by assert statement. We recommend you to follow-up our tutorial on assert statement in python http://codeofgeeks.com/assert-statement-in-python-with-example/ for more information.

Example code

n = 7
assert n%2==0, "Odd Integers are not allowed !"
print("Square of {0} is {1}".format(n, n*n))

O/P

Traceback (most recent call last):
File “”, line 2, in
AssertionError: Odd Integers are not allowed !

Above code will not execute as it has the assertion error.

We can handle this using AssertionError class.

try:
    n = 7
    assert n%2==0, "Odd Integers are not allowed !"
    print("Square of {0} is {1}".format(n, n*n))
except AssertionError as a:
    print('Assertion Exception encountered.')
    print('Details are: ', a)

O/P

Assertion Exception encountered.
Details are: Odd Integers are not allowed !

In the above code, we have used AssertionError class that will allow us to handle the error raised by assert statement in python.



4. Type Error Exception in Python

Use of TypeError exception class is helpful in handling all the errors that are raised when an operation is applied to an object of inappropriate datatype.

Example code

# program to increment a value
def increment(n):
    try:
        print('Incremented value: ', n+1)
    except TypeError as t:
        print('Type Error Exception encountered.')
        print('Details are: ', t)
        
n = 'I am a string'
increment(n)

O/P

Type Error Exception encountered.
Details are: can only concatenate str (not “int”) to str

In the above code, we have used TypeError class that will allow us to handle the error raised when an operation of datatype is performed on other.



5. Value Error Exception in Python

Use of ValueError exception class is helpful in handling all the errors that are raised when an operation or function receives an argument with right datatype but wrong value.

Like, finding square root of negative number will give ValueError. Let’s handle this,

Example code

# program to find square root
import math
def square_root(n):
    try:
        print('Result: ', math.sqrt(n))
    except ValueError as v:
        print('Value Error Exception encountered.')
        print('Details are: ', v)
        
n = -4
square_root(n)

O/P

Value Error Exception encountered.
Details are: math domain error

In the above code, we have used ValueError class that will allow us to handle the error raised when we passed negative value to find the square root of.



6. Key Error Exception in Python

Use of KeyError exception class is helpful in handling all the errors that are raised when a given mapping key is not found in the set of existing keys.

Like, finding a key in a dictionary that does not even exists, will result in KeyError.

Let’s handle this,

Example code

# program to find non-existing key
def find_key():
    try:
        d = {1: 'one', 2: 'two', 3: 'three'}
        print(d[4]) # printing value of key 4 which is not present
    except KeyError as k:
        print('Key Error Exception encountered.')
        print('Details are: ', k)
        
find_key()

O/P

Key Error Exception encountered.
Details are: 4

In the above code, we have used KeyError class that will allow us to handle the error raised when we tried to access the key which is not present.



7. Name Error Exception in Python

Use of NameError exception class is helpful in handling all the errors that are raised when an identifier (variable or method) is not found locally or globally.

Like, printing a value of a variable which is not declared.

Let’s handle this,

Example code

try:
    a = 10
    print(b)
except NameError as n:
    print('Name Error Exception encountered.')
    print('Details are: ', n)

O/P

Name Error Exception encountered.
Details are: name ‘b’ is not defined

In the above code, we have used NameError class that will allow us to handle the error raised when we tried to print a variable which is not declared.

8. Index Error Exception in Python

Use of IndexError exception class is helpful in handling all the errors that are raised when a given index is out of range.

Like, accessing a sixth element in a list of 5 element.

Let’s handle this,

Example code

try:
    l = [10, 20, 30, 40, 50]
    print(l[5]) # 0-based indexing
except IndexError as i:
    print('Index Error Exception encountered.')
    print('Details are: ', i)

O/P

Index Error Exception encountered.
Details are: list index out of range

In the above code, we have used IndexError class that will allow us to handle the error raised when we tried to access the 6th element of the list.

So, above are the most common types of exceptions in python while there are lot more these are most talked about.



NEXT TUTORIAL >> User Defined Exceptions in Python

Tags: Arithmetic error handling in PythonCommon exceptions in Python with examplesDealing with value errors in PythonDifferentiating between exceptions in PythonException classes in PythonException propagation in PythonHandling name error exception in PythonHandling runtime errors in PythonHandling type error exception in PythonHandling undefined variables in Python (NameError)Index error exception in Python explainedIndex out of range exception in PythonPython arithmetic error exception examplePython assertion error exception tutorialPython built-in exception classesPython dictionary key error exception examplePython exception catching techniquesPython exception handling tutorialPython exception hierarchy explainedPython exception types and usesPython key error exception tutorialPython type error exception tutorialtypes of exceptions in pythonTypes of exceptions in Python with examplesUsing assert statement in Python with exceptionsValue error exception in Python with examples
  • Previous User Defined Exceptions in Python with Examples
  • Next Exception Handling in Python with examples

Leave a Reply Cancel reply

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

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.