Python

Understanding Exception Handling in python

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

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

2 years ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers.… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

3 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

3 years ago