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. We have covered about exceptions and errors in python in the last tutorial.
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:
Now think that one day you are using Studytonight's 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
try block, we write the code in which there are chances of any error or exception to occur.
except block is responsible for catching the exception and executing the statements specified inside it.
Below we have the code performing division by zero:
a = 10 b = 0 print("Result of Division: " + str(a/b))
Traceback (most recent call last): File "main.py", line 3, in <module> print("Result of Division: " + str(a/b)) ZeroDivisionError: division by zero
The above code leads to exception and the exception message is printed as output on the console.
If we use the
except block, we can handle this exception gracefully.
# try block try: a = 10 b = 0 print("Result of Division: " + str(a/b)) except: print("You have divided a number by zero, which is not allowed.")
You have divided a number by zero, which is not allowed.
As you can see in the code example above, the
try block is used to put the whole code that is to be executed in the program(which you think can lead to exception), if any exception occurs during execution of the code inside the
try block, then it causes the execution of the code to be directed to the
except block and the execution that was going on in the
try block is interrupted. But, if no exception occurs, then the whole
try block is executed and the
except block is never executed.
try block is generally followed by the
except block which holds the exception cleanup code(exception has occured, how to effectively handle the situation) like some
In the except block, along with the keyword
except we can also provide the name of exception class which is expected to occur. In case we do not provide any exception class name, it catches all the exceptions, otherwise it will only catch the exception of the type which is mentioned.
Here is the syntax:
# except block except(<Types of Exceptions to catched>): # except block starts
If you notice closely, we have mentioned types of exceptions, yes, we can even provide names of multiples exception classes separated by comma in the except statement.
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.")
You have divided a number by zero, which is not allowed. 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
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
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
Try running the above code, provide 0 as value for the denominator and see what happens and then provide some string(non-integer) value for any variable. We have handled both the cases in the above code.
As you can see in the above example we printed different messages based on what exception occured. If you do not have such requirements where you need to handle different exception individually, you can catch a set of exceptions in a single exception block as well.
Here is above the above code with a single
# try block try: a = int(input("Enter numerator number: ")) b = int(input("Enter denominator number: ")) print("Result of Division: " + str(a/b)) # except block handling division by zero except(ValueError, ZeroDivisionError): print("Please check the input value: It should be an integer greater than 0")
here we have handled both the exceptions using a single
except block while showing a meaningful message to the user.
exceptblock to Handle unknown Exceptions
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 block handling division by zero except(ZeroDivisionError): print("You have divided a number by zero, which is not allowed.") # except block handling wrong value type except(ValueError): 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
In the coming tutorials we will learn about
finally block and how to raise an exception using the