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

JENKINS BASICS

  Jenkins  – an open source automation server which enables developers around the world to reliably build, test, and deploy their software. Dashboard: " Dashboard " is the default view shown when you open Jenkins and shows an overview of all  projects configured on a  Jenkins  instance. Creating a New Project: Step 2:  In the next screen, enter the Item name, Choose the ‘Freestyle project option’ Step 3  − The following screen will come up in which you can specify the details of the job. Note  − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from the remote repository. Step 4 − Now go to the Build section and click on Add build step → Execute Windows batch command Before Executing and building a file. Let me describe the task which w...

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