In the last tutorial, we learned about Python exceptions. We know that exceptions abnormally terminate the execution of a program.
This is why it is important to handle exceptions. In Python, we use the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 0 block
Python try...except Block
The try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 0 block is used to handle exceptions in Python. Here's the syntax of try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 0 block:
try: # code that may cause exception except: # code to run when exception occursHere, we have placed the code that might generate an exception inside the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 block. Every try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 block is followed by an try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5 block.
When an exception occurs, it is caught by the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5 block. The try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5 block cannot be used without the try block.
Example: Exception Handling Using try...except
try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0.In the example, we are trying to divide a number by 0. Here, this code generates an exception.
To handle the exception, we have put the code, try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 8 inside the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 block. Now when an exception occurs, the rest of the code inside the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 block is skipped.
The try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5 block catches the exception and statements inside the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5 block are executed.
If none of the statements in the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 block generates an exception, the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5 block is skipped.
Catching Specific Exceptions in Python
For each try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 block, there can be zero or more try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5 blocks. Multiple try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5 blocks allow us to handle each exception differently.
The argument type of each try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5 block indicates the type of exception that can be handled by it. For example,
try: even_numbers = [2,4,6,8] print(even_numbers[5]) except ZeroDivisionError: print("Denominator cannot be 0.") except IndexError: print("Index Out of Bound.") # Output: Index Out of BoundIn this example, we have created a list named even_numbers.
Since the list index starts from 0, the last element of the list is at index 3. Notice the statement,
print(even_numbers[5])Here, we are trying to access a value to the index 5. Hence, try: even_numbers = [2,4,6,8] print(even_numbers[5]) except ZeroDivisionError: print("Denominator cannot be 0.") except IndexError: print("Index Out of Bound.") # Output: Index Out of Bound9 exception occurs.
When the try: even_numbers = [2,4,6,8] print(even_numbers[5]) except ZeroDivisionError: print("Denominator cannot be 0.") except IndexError: print("Index Out of Bound.") # Output: Index Out of Bound9 exception occurs in the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 block,
- The print(even_numbers[5])2 exception is skipped.
- The set of code inside the try: even_numbers = [2,4,6,8] print(even_numbers[5]) except ZeroDivisionError: print("Denominator cannot be 0.") except IndexError: print("Index Out of Bound.") # Output: Index Out of Bound9 exception is executed.
Python try with else clause
In some situations, we might want to run a certain block of code if the code block inside try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 runs without any errors.
For these cases, you can use the optional print(even_numbers[5])5 keyword with the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 statement.
Let's look at an example:
# program to print the reciprocal of even numbers try: num = int(input("Enter a number: ")) assert num % 2 == 0 except: print("Not an even number!") else: reciprocal = 1/num print(reciprocal)Output
If we pass an odd number:
Enter a number: 1 Not an even number!If we pass an even number, the reciprocal is computed and displayed.
However, if we pass 0, we get print(even_numbers[5])2 as the code block inside print(even_numbers[5])5 is not handled by preceding try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 5.
Enter a number: 0 Traceback (most recent call last): File "", line 7, in reciprocal = 1/num ZeroDivisionError: division by zeroNote: Exceptions in the print(even_numbers[5])5 clause are not handled by the preceding except clauses.
Python try...finally
In Python, the # program to print the reciprocal of even numbers try: num = int(input("Enter a number: ")) assert num % 2 == 0 except: print("Not an even number!") else: reciprocal = 1/num print(reciprocal)1 block is always executed no matter whether there is an exception or not.
The # program to print the reciprocal of even numbers try: num = int(input("Enter a number: ")) assert num % 2 == 0 except: print("Not an even number!") else: reciprocal = 1/num print(reciprocal)1 block is optional. And, for each try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 block, there can be only one # program to print the reciprocal of even numbers try: num = int(input("Enter a number: ")) assert num % 2 == 0 except: print("Not an even number!") else: reciprocal = 1/num print(reciprocal)1 block.
Let's see an example,
try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") finally: print("This is finally block.")Output
Error: Denominator cannot be 0. This is finally block.In the above example, we are dividing a number by 0 inside the try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") # Output: Error: Denominator cannot be 0. 3 block. Here, this code generates an exception.