Codied To Clipboard !
Home > Notes > python
Exception handling is a concept used in Python to handle the exceptions and errors that occur during the execution of any program. Exceptions are unexpected errors that can occur during code execution. Well, yes, exception occur, there can be errors in your code, but why should we invest time in handling exceptions? The answer to this question is to improve User Experience. When an exception occurs, following things happen: Program execution abruptly stops. The complete exception message along with the file name and line number of code is printed on console. All the calculations and operations performed till that point in code are lost. Now think that one day you are using codeshunger website, you click on some link to open a tutorial, which, for some unknown reason, leads to some exception. If we haven’t handled the exceptions then you will see exception message while the webpage is also not loaded. Will you like that? Hence, exception handling is very important to handle errors gracefully and displaying appropriate message to inform the user about the malfunctioning.
For handling exceptions in Python we use two types of blocks, namely, try block and except block. In the try block, we write the code in which there are chances of any error or exception to occur. Whereas the except block is responsible for catching the exception and executing the statements specified inside it.
# try block try: a = 10 print("Result of Division: " + str(a/b)) except: print("You have divided a number by zero, which is not allowed")
Another important point to note here is that code execution is interrupted in the try block when an exception occurs, and the code statements inside the try block after the line which caused the exception are not executed. The execution then jumps into the except block. And after the execution of the code statements inside the except block the code statements after it are executed, just like any other normal execution. Let’s take an example
# try block try: a = 10 b = 0 print("Result of Division: " + str(a/b)) print("No! This line will not be executed.") except: print("You have divided a number by zero, which is not allowed # outside the try-except blocks print("Yo! This line will be executed.")
There are multiple ways to accomplish this. Either we can have multiple except blocks with each one handling a specific exception class or we can handle multiple exception classes in a single except block. Multiple except blocks If you think your code may generate different exceptions in different situations and you want to handle those exceptions individually, then you can have multiple except blocks. Mostly exceptions occur when user inputs are involved. So let’s take a simple example where we will ask user for two numbers to perform division operation on them and show them the result. We will try to handle multiple possible exception cases using multiple except blocks.
# try block try: a = int(input("Enter numerator number: ")) b = int(input("Enter denominator number: ")) print("Result of Division: " + str(a/b)) except (ZeroDivisionError): # except block handling division by zero print("You have divided a number by zero, which is not allowed except (ValueError): # except block handling wrong value type print("You must enter integer value")
Although we do try to make our code error free by testing it and using exception handling but there can be some error situation which we might have missed. So when we use except blocks to handle specific exception classes we should always have a generic except block at the end to handle any runtime excpetions(surprise events).
# try block try: a = int(input("Enter numerator number: ")) b = int(input("Enter denominator number: ")) print("Result of Division: " + str(a/b)) except (ZeroDivisionError): # except block handling division by zero print("You have divided a number by zero, which is not allowed except (ValueError): # except block handling wrong value type print("You must enter integer value") #generic except block except: print("Oops! Something went wrong!") ''' In the code above the first except block will handle the ZeroDivisionError, second except block will handle the ValueError and for any other exception that might occur we have the third except block. '''
The finally code block is also a part of exception handling. When we handle exception using the try and except block, we can include a finally block at the end. The finally block is always executed, so it is generally used for doing the concluding tasks like closing file resources or closing database connection or may be ending the program execution with a delightful message.
#try block try: a = int(input("Enter numerator number: ")) b = int(input("Enter denominator number: ")) print("Result of Division: " + str(a/b)) except (ZeroDivisionError): # except block handling division by zero print("You have divided a number by zero, which is not allowed finally: print("Code execution Wrap up!") # outside the try-except block print("Will this get printed?")