• 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

Exception Handling in Python with examples

  • January 2, 2023
  • CODE OF GEEKS
  • 0

NEXT TUTORIAL >> Types of Exceptions in Python

What is an Exception ?

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.



Why Exception Handling ?

The main aim of Exception Handling is to make the program robust. Robust means reliable. When we handle exceptions in our code, we make sure that when there is an error, our program logs it and continue the execution.

Exception Handling is one of the best practice in the process of software development.

Analysis on Exception Handling in Python

All exceptions are represented as classes in Python. Built-in Exceptions are the exceptions that are already available in Python like OSError.

Base class (or parent class) for all built-in exceptions is BaseException class. This class is further inherited by Exception class. From Exception class, the subclasses ‘StandardError‘ and ‘Warning‘ is derived.

Exception Classes in Python
Exception Classes in Python

Exceptions are defined as subclasses under StandardError. These Exceptions are mandatory to be handled or else our program will not execute.

On the other hand, Warning represents the caution and does not interrupts the program flow, if left unhandled.

Python also provides the utility to create User Defined Exceptions. When a developer creates his/her own exception class, then, this class should be derive from Exception class.



Steps to handle an Exception in Python

1. Cover the lines of code that have the possibility of throwing the exception under try block.

try:
  # statements

Whenever an exception occurs in the code written inside try block, then, program will not be terminated. Rather, PVM starts checking for except block which is responsible to handle the exception.

2. Use of except block to handle the exception caught. (Find in detail below)

3. Lastly, all the mandatory actions like closing of a file, closing a database connection is usually written inside finally block. This is due to the fact that the statements inside the finally block are executed irrespective of whether there is an exception or not.

try:
  # statements
except ExceptionName:
  # statements
finally:
  # statements

This is how you handle exceptions in Python.



Extra Gyan !!

Please note that, handling an exception does not mean that you are preventing it but you are just preventing the damage it may cause.

Let’s see one example code to handle some popular exceptions in Python,

def find_divisor(n1, n2):
    try:
        res = n1/n2
        print('Result is : ', res)
        print('All went good !!')
    except ArithmeticError:
        print('No worries, we have handled the exception')
    finally:
        print('In the finally block')
    print('Out of try-except-finally\n')
print('******First Call******')
find_divisor(20, 10)
print('******Second Call******')
find_divisor(20, 0)

O/P

******First Call******
Result is : 2.0
All went good !!
In the finally block
Out of try-except-finally

******Second Call******
No worries, we have handled the exception
In the finally block
Out of try-except-finally

Observe the above code carefully, our first function call is exception-free and we can see proper output. But, in our second call, we deliberately passing 0 as our denominator, which indeed is ‘ZeroDivisionError‘. Hence, we didn’t got any result.

Note that finally block was executed in both cases.

Do this !!

Remove try-except block from above code, see what happens.



Printing the Type of Exception

Instead of printing things manually, we can simply print the name of the exception that was originally caught. To do this, modify except block as:

except Exception as e:
  print(e)

In the above method, we are catching an exception as object and then printing it.

Important points on Exception Handling

* We can have multiple except blocks within a same try block.
try:
  # statements
except Exception1:
  # handler
except Exception2:
  # handler
except Exception3:
  # handler
except (Exception4, Exception5):
  # handler
finally:
  # statements
* try-except-else-finally also exists.

If no exception is raised then the statements inside else statements are executed.

try:
  # statements
except Exception1:
  # handler
except Exception2:
  # handler
except Exception3:
  # handler
else:
  # statements
finally:
  # statements
* We can not write except with try, but vice-versa is possible.

Truth has been said.

* finally block is optional to use

Truth has been said.



That’s all here in ‘Exception Handling in Python’.

NEXT TUTORIAL >> Types of Exceptions in Python



Tags: catch exception python and continueerror handling in pythonerror handling json pythonerror handling python functionerror handling python lambdaerror handling python open fileerror handling python raiseerror handling python stack overflowerror handling python try exceptexample for exception in pythonexception handling decorator pythonexception handling in pythonexception handling in python boto3exception handling in python by durga sirexception handling in python divide by 0exception handling in python exercisesexception handling in python hierarchyexception handling in python hindiexception handling in python notesexception handling in python pdfexception handling in python vs javaexception handling in python with examplesexception handling multiprocessing pythonexception handling pythonexception handling python 3exception handling python best practicesexception handling python codeexception handling python exampleexception handling python not definedexception handling python pptexception handling python seleniumexception handling python tryexception handling python valueexception handling python with statementexception in beautifulsoup pythonexception in except pythonexception in generator pythonexception in if pythonexception in loop pythonexception in python codeexception in python dictionaryexception in python exitexception in python in hindiexception in python javatpointexception in python keywordexception in python raiseexception in python tutorialexception in python valueexception in return pythonexceptions in python with examplesexceptions module in python 3grpc exception handling pythonhandle exception python loophandling exceptions in python hackerrank solutionhow exception is handled in pythonhow many except statement in pythonhow throw exception in pythonhow to avoid exception in pythonhow to do exception handling in pythonhow to use exception handling in pythonimportance of exception handling in pythonin python exception handlingis error handling and exception handling are samekafka consumer exception handling pythonprint exception in pythonprogram for exception handling in pythonpython 2.4 exception handlingpython exception get causepython exception handling best practicespython exception handling divide by zeropython exception handling errno 2python exception handling exercisespython exception handling functionpython exception handling get error messagepython exception handling hierarchypython exception handling librarypython exception handling using try except and finally statementpython file exception handling examplepython raise exception examplepython raise vs raise exceptionpython zeep exception handlingtypes of exception handling in pythonurllib exception handling python 3what are the benefits of exception handlingwhat is exception handling in pythonwhat is exception handling pythonwhat is exception in pythonwhy exception handling in pythonwhy we use exception handling in pythonwith exception handling python
  • Previous Types of Exceptions in Python with Examples
  • Next Types of Errors 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.