Understanding Exception Handling in python

Sharing is caring!

In my last python tutorial series, we learned the basic concept for python with a few simple examples. If you want to learn those tutorials, I would be recommended to go please check all my tutorials. Here is the link Python OOPS concept with Class, Object and Constructor, 
concept of variablesdata typesconditional control, functional control,  Module, and packages and Data Structure (List, Dictionary, and Set) of python.

Now in this series, we learn the exception handling in python. As we know any program which throws abnormal condition at the run time is called an exception. Most of the confusion about the error and exception. An error is kind of syntax error and exception is throw an error at run time. An exception is implemented by two main class in python that is BaseException and Exception.

Statement: try..except..else..finally

Now Let’s see the order of exception witch is declaed the above in statement. This is very important to understand.

First, the try clause is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs during the execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.

If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops. If not exception, once try block is executed, else will also get executed Whatever the case, finally block will get executed.

Except clause
try:
	<statement>
except:
	<catch all exception>
Catch Particular exception
try:
	<statement>
except <exception name>:
	<catch one exception>
Catch multiple exception with common handling
try:
	<statement>
except (exp1, exp2):
	<catch multiple exception>

 

In the above clause, it is cleared that exception can occur should be in a try block and handled the exception with except keyword with proper. We can catch multiple exceptions in one block and multiple blocks also. Please see the clause in the blow to handle the multiple exceptions in multiple catches and a single block with the mutpile exception catche.

Multiple except clause
try:
	<statement>
except exp1:
	<catch exp1 exception>
except exp 2:
	<catch exp2 exception>
except:
	<catch rest all exception>
Try.. Except.. Else clause
try:
	<statement>
except:
	<catch all exception>
else:
	<else handller>

Let’s get understand by an example to understand in better way.

a = [1,2,3]
try:
	print a[10]
except IndexError as err:
	print err.args
	print err

As we can see in the above example it gives the exception while executing in print a[10] because this index is out of range. So we need to handle or catch by IndexError. Here we can add the finally block also it required to execute a certain statement. Generally, we used the finally block to clean the steam or close the database connection if it used. It makes our programme to avoid certain memory leaks.

try:
   <statment>
except: 
    <statement>
finally:
     <statement>

Let’s see this by an example.

def func():
	a = [1,2,3]
	try:
		print a[10]
		#print a[0]
	except:
		print 'exception'
		return
	finally:
		print 'in final block'

Now if the user wants to declare their own exception then definitely can be defined. As I said that python is a very versatile language to make thing simple and easy. The class should be inherited from Exception. Let’s see the statement or clause to understand by and example.

class MyException(Exception):
	def __init__(self, error):
		self.error = error

a = [1,2,3]
try:
	raise MyException('my exp: index out of range')
except MyException as e:
	print e.error

Summary: Now we have a good understanding of the Exception Handling of python. We have seen few examples and play around it to clear the doubts. If you still having issue or doubts then please add a comment I will try to reply as much possible. In my next python tutorial series, we will learn about the Files of python with the example.

If you are wondering to learn Android then Please Learn from Android category and Wondering to lean Kotlin then Kotlin Category will help you. If you learn all python article then learn from the python category.

Please do subscribe your email to get the newsletter on this blog on below and if you like this post then do not forget to share like and comment on below section.

Happy coding 🙂

 

0 0 votes
Article Rating
Understanding Exception Handling in python
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Scroll to top
0
Would love your thoughts, please comment.x
()
x