Python-Exception Handling

Exception handling, Error handling, and logging are the import aspects of any programming language, whether being Python, Java, or any other language. In this post, I will cover how we can perform error handling in Python. Error handling makes the code more robust and helps in debugging easily when any error occurs.

When the normal flow of the execution of the program is interrupted, an exception occurs. In python, an exception is an object that represents error. Exception handling allows the scripting to function in the desired ways, say you are aware what kind of the exception can happen in your code and what steps need to be taken to avoid the exception or you want to stop the script to execute another steps or function when any error or exception occur, you can use the error handling for this.

In Python, error handling can be performed in multiple ways, our focus will be on try/except or try/except/finally. Using the sample code we will understand the difference between try/exception and try/exception/finally.

 

Try and exception block in Python is used to catch and handle the exceptions. Critical code that can raise the exception is kept inside the try block and the code that handles the exception is kept inside except block. When code is executed Python goes to the try block first, if there is no error and exception it will execute the code in the try block and goes to the next step. If any exception occurs then it goes to except block.

As per docs.python.org:

  • If any exception error in the try block it will be handled by except block. If the exception is not handled by the except block, code will invoke the finally block before again raising the exception
  • If any exception occurs during the execution of the except block, the exception will be raised after executing the finally block
  • If the try block is having the break or return or continue statements, finally block will be executed before the break or return or continue statement. I will take an example to evaluate this
  • If the try and finally block is having the return statement, the return statement will return the value from the final block, not from the try block
1)	Execute the code without an exception
a= 5
def python_func():
try:
    		print('value of a ', a)
except:
   	 print('value is not defined')

python_func()

‘’’ OUTPUT  value of a  5’’’

2)	Raise exception for a negative value
a = -2
def python_func():
try:
   		if a > 0:
            		print('Value of a :', a)
        	else:
          	  	raise ValueError('Provide positive number...') 
except ValueError as ve:
    	print(ve)

python_func()

‘’’OUTPUT  ValueError: Provide positive number...’’’

3)	Exception with finally block.
Let’s divide a number by 0. Return the values in the try, except and finally block
def python_func():
    try:
        print(4/0)
        return 1 
    except:
        print('Divide by zero error')
        return 2
    finally:
        print('Executing the final block')
        return 3
Divide by zero error
Executing the final block
3

When the function divides 4/0, it will raise an exception and goes to the exception block. In the exception block, there is a print statement. In last it goes to the final block and prints the final block statement as well return the value of the return statement which is 3. From the above code it is clear if we are having any return statement in the final and try blocks, function will always return the value from the final block only.

Click on the link to find the video on how to implement the Exception Handling

Kindly share your feedback and questions and subscribe Hadoop Tech, our facebook page(Hadoop Tech), and you tube (You Tube Channel)for more articles. Follow on GitHub

Leave a comment