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

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...

NumPY In python

 NumPy Stands for numerical python How do I install NumPy? To install Python NumPy, go to your command prompt and type “pip install numpy”.  Once the installation is completed, go to your IDE (For example: PyCharm) and simply import it by typing:  “import numpy as np” Here, I have different elements that are stored in their respective memory locations. It is said to be two dimensional because it has rows as well as columns. In the above image, we have 3 columns and 4 rows available. How do I start NumPy? Single-dimensional Numpy Array: 1 2 3 import numpy as np a = np.array([ 1 , 2 , 3 ]) print (a) Output – [1 2 3] Multi-dimensional Array: 1 2 a = np.array([( 1 , 2 , 3 ),( 4 , 5 , 6 )]) print (a) O/P – [[ 1 2 3] [4 5 6]] Python NumPy Array v/s List Why NumPy is used in Python? We use python NumPy array instead of a list because of the below three reasons: Less Memory Fast Convenient The very first reason to choose python NumPy array is that it occupies less memory as co...