In the last tutorial, we learned about Python exceptions. We know that exceptions abnormally terminate the execution of a program. Show This is why it is important to handle exceptions. In Python, we use the 0 blockPython try...except BlockThe 0 block is used to handle exceptions in Python. Here's the syntax of 0 block:
Here, we have placed the code that might generate an exception inside the 3 block. Every 3 block is followed by an 5 block.When an exception occurs, it is caught by the 5 block. The 5 block cannot be used without the try block.Example: Exception Handling Using try...except
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, 8 inside the 3 block. Now when an exception occurs, the rest of the code inside the 3 block is skipped.The 5 block catches the exception and statements inside the 5 block are executed.If none of the statements in the 3 block generates an exception, the 5 block is skipped.Catching Specific Exceptions in PythonFor each 3 block, there can be zero or more 5 blocks. Multiple 5 blocks allow us to handle each exception differently.The argument type of each 5 block indicates the type of exception that can be handled by it. For example,
In 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,
Here, we are trying to access a value to the index 5. Hence, 9 exception occurs.When the 9 exception occurs in the 3 block,
Python try with else clauseIn some situations, we might want to run a certain block of code if the code block inside 3 runs without any errors.For these cases, you can use the optional 5 keyword with the 3 statement.Let's look at an example:
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. Enter a number: 4 0.25 However, if we pass 0, we get 2 as the code block inside 5 is not handled by preceding 5.Enter a number: 0 Traceback (most recent call last): File "", line 7, in reciprocal = 1/num ZeroDivisionError: division by zero Note: Exceptions in the 5 clause are not handled by the preceding except clauses.Python try...finallyIn Python, the 1 block is always executed no matter whether there is an exception or not.The 1 block is optional. And, for each 3 block, there can be only one 1 block.Let's see an example,
Output Error: Denominator cannot be 0. This is finally block. In the above example, we are dividing a number by 0 inside the 3 block. Here, this code generates an exception. |