Skip to main content

Exception Handling in Python

 

Introduction

 

An error is an abnormal condition that results in unexpected behavior of a program. Common kinds of errors are syntax errors and logical errors. Syntax errors arise due to poor understanding of the language. Logical errors arise due to poor understanding of the problem and its solution.

 

Anomalies that occur at runtime are known as exceptions. Exceptions are of two types: synchronous exceptions and asynchronous exceptions. Synchronous exceptions are caused due to mistakes in the logic of the program and can be controlled. Asynchronous exceptions are caused due to hardware failure or operating system level failures and cannot be controlled.

 

Examples of synchronous exceptions are: divide by zero, array index out of bounds, etc.) . Examples of asynchronous exceptions are: out of memory error, memory overflow, memory underflow, disk failure, etc. Overview of errors and exceptions in Python is as follows:

 

types-of-errors

 

Handling Exceptions

 

Flowchart for exception handling process is as follows:

 

exception-handling-flowchart

 

We can handle exceptions in Python code using try and except blocks. Statements which can raise exceptions are placed in try block. Code that handles the exception is placed in except block. The code that handles an exception is known as exception handler and this process is known as exception handling.

 

try and except

 

Syntax for using try and except for exception handling is as follows:

 

 

Following is an example for handling divide by zero exception using try and except blocks:

 

 

Multiple Except Blocks

 

Often, there will be a need to handle more than one exception raised by a try block. To handle multiple exceptions, we can write multiple except blocks as shown below:

 

 

Following is an example for handling multiple exceptions using multiple except blocks:

 

 

In the previous example for input 10 and 0, the output displayed is “Denominator cannot be zero”. When the divide by zero exception was triggered in try block, first two except blocks were skipped as the type of exception didn’t match with either NameError or ValueError. So, third except block was executed.

 

Multiple Exceptions in a Single Block

 

We can handle multiple exceptions using a single except block as follows:


 

Following is an example which demonstrates handling multiple exceptions using a single except block:

 

 

Handle Any Exception

 

In some cases, we might want to execute the same code (handler) for any type of exception. Such common handler can be created using except as follows:

 

 

Following is an example which demonstrates handling any exception with a single except block:

 

 

else Clause

The try and except blocks can be followed by an optional else block. The code in else block executes only when there is no exception in the try block. The else block can be used to execute housekeeping code like code to free the resources that are being used.

 

Handling Exceptions in Functions

 

We can use try and except blocks inside functions as we are using until now. In the try block, we can call a function. If this function raises an exception, it can be handled by the except block which follows the try block. Following example demonstrates handling exceptions in functions:

 

 

finally block

 

A try block must be followed by one or more except blocks or one finally block. A finally block contains code that executes irrespective of whether an exception occurs or not. Syntax for finally block is as follows:

 

 

The finally block is generally used to write resource freeing code. We cannot write a else block along with finally block.

 

Built-in Exceptions

 

There are several built-in or pre-defined exceptions in Python. Python automatically recognizes the built-in exceptions and handles them appropriately. Following are some of the built-in exceptions in Python:

 

ExceptionDescription
ExceptionBase class for all exceptions
StandardErrorBase class for all built-in exceptions (excluding StopIteration and SystemExit)
SystemExitRaised by sys.exit() function
ArithmeticErrorBase class for errors generated by mathematical calculations
OverflowErrorRaised when the maximum limit of a numeric type exceeds
FloatingPointErrorRaised when a floating point error could not be raised
ZeroDivisionErrorRaised when a number is divided by zero
AssertionErrorRaised when the assert statement fails
AttributeErrorRaised when attribute reference or assignment fails
EOFErrorRaised when end-of-file is reached or there is no input for input() function
ImportErrorRaised when an import statement fails
LookupErrorBase class for all lookup errors
IndexErrorRaised when an index is not found in a sequence
KeyErrorRaised when a key is not found in the dictionary
NameErrorRaised when an identifier is not found in local or global namespace
IOErrorRaised when input or output operation fails
SyntaxErrorRaised when there is syntax error in the program
ValueErrorRaised when the value of an argument is invalid
RuntimeErrorRaised when the generated error does not fall into any of the above categories
NotImplementedErrorRaised when an abstract method that needs to be implemented is not implemented in the derived class
TypeErrorRaised when two incompatible types are used in an operation

 

 

Comments

Popular posts from this blog

Is-A and Has-A relationships in python

  In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. #Is-A relationship --> By Inheritance class  A:    def   __init__ ( self ):      self .b= 10    def   mym1 ( self ):      print ( 'Parent method' ) class  B(A):    def   mym2 ( self ):      print ( 'Child method' ) d = B() d.mym1() #output: Parent method d.mym2() #output: Child method HAS-A Relationship:  Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom. Let’s understand these concepts with an example of Car class. # Has-A relationship --> By Composition class  Engine:    def   __init__ ( self ):      s

Magic Methods in Python

  What Are Dunder Methods ? In Python, special methods are a set of predefined methods you can use to enrich your classes.  They are easy to recognize because they start and end with double underscores, for example  __init__  or  __str__ . Dunder methods let you emulate the behavior of built-in types.  For example, to get the length of a string you can call  len('string') . But an empty class definition doesn’t support this behavior out of the box: These “dunders” or “special methods” in Python are also sometimes called “magic methods.” class NoLenSupport : pass >>> obj = NoLenSupport () >>> len ( obj ) TypeError : "object of type 'NoLenSupport' has no len()" To fix this, you can add a  __len__  dunder method to your class: class LenSupport : def __len__ ( self ): return 42 >>> obj = LenSupport () >>> len ( obj ) 42 Object Initialization:  __init__ "__init __ " is a reserv

Architechture of Kubernetes

  Kubernetes Architecture and Components: It follows the client-server architecture, from a high level, a Kubernetes environment consists of a  control plane (master) , a  distributed storage system  for keeping the cluster state consistent ( etcd ), and a number of  cluster nodes (Kubelets). We will now explore the individual components of a standard Kubernetes cluster to understand the process in greater detail. What is Master Node in Kubernetes Architecture? The Kubernetes Master (Master Node) receives input from a CLI (Command-Line Interface) or UI (User Interface) via an API. These are the commands you provide to Kubernetes. You define pods, replica sets, and services that you want Kubernetes to maintain. For example, which container image to use, which ports to expose, and how many pod replicas to run. You also provide the parameters of the desired state for the application(s) running in that cluster. API Server: The  API Server  is the front-end of the control plane and the only