<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged try-except</title>
<link>https://coderlegion.com/tag/try-except</link>
<description>Powered by Question2Answer</description>
<item>
<title>Python Opening &amp; Reading Files</title>
<link>https://coderlegion.com/186/python-opening-reading-files</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Sometimes, when you are working in your program, a situation comes where &lt;strong&gt;file handling is used&lt;/strong&gt; for performing operations on the file. However, after completing the operation, you must &lt;strong&gt;close the file&lt;/strong&gt;. Also, when you use the &lt;strong&gt;database connection&lt;/strong&gt; in your program, the &lt;strong&gt;connection needs to be closed&lt;/strong&gt; after the task completion. Wondering &lt;em&gt;how you can achieve it&lt;/em&gt; by using exception handling? It is quite easy because you simply  put that code in the &lt;strong&gt;finally block&lt;/strong&gt; after the try and except block during your program development. In this article, I will cover the detailed overview of the finally block, when it is needed, its purpose, and some examples with the help of code. Let's get started.&lt;/p&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Finally Block in Python: An Overview&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In Python, the finally block is another key concept of exception handling after try and except block. This expression is used as &lt;strong&gt;code cleaning action&lt;/strong&gt; or &lt;strong&gt;logic cleaning&lt;/strong&gt; in programming, which means when you use the resource of a computer, you have to return it after achieving the result. Additionally, the finally block is &lt;strong&gt;utilized for resource management.&lt;/strong&gt; While working with try and except block, you put the piece of &lt;strong&gt;code in the finally block&lt;/strong&gt; that needs to be &lt;strong&gt;executed&lt;/strong&gt; regardless of an &lt;strong&gt;exception occurrence&lt;/strong&gt;.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Finally Block: Definition&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; The finally block in exception handling is the block used in &lt;strong&gt;conjunction with the try-except block&lt;/strong&gt;. It defines the piece-of-code that needs to be executed at the end, whether the exception occurs or not. The code written inside this block is used as a cleaning operation. It also ensures that whether the exception is encountered in the try block or handled in the except block, the finally block will always execute the code inside it.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Syntax for Finally Block&lt;/h3&gt;
&lt;pre&gt;  &lt;code&gt; 
try:   
#code that needs to be tested and can cause an exception   
pass   

except exception1:   
#code to handle the exception1   
pass 
   
finally: 
#code that needs to run whether exceptions occur or not 
pass 
&lt;/code&gt;  &lt;/pre&gt;  
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Purpose of Finally Block&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; The finally block has a very crucial role in programming language. It is not just a simple block that will &lt;strong&gt;execute whether errors occur or not&lt;/strong&gt;, but it will &lt;strong&gt;manage the code&lt;/strong&gt; and make the program robust. The purpose of the finally block in exception handling is:&lt;/p&gt; 
&lt;ul&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; It is used for cleanup activities when you are working in the program using the file. At the end, you can put the close file code in the finally block that &lt;strong&gt;ensures the resource is released&lt;/strong&gt; without creating any problems. Also, it ensures resource management like network connection and database connection closing that &lt;strong&gt;resolves&lt;/strong&gt; the issue of &lt;strong&gt;resource leak&lt;/strong&gt; and &lt;strong&gt;deadlock conditions.&lt;/strong&gt;&lt;/li&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; The code that is &lt;strong&gt;compulsory&lt;/strong&gt; to run regardless of &lt;strong&gt;exception occurrence or not&lt;/strong&gt; will also be achieved by using the finally block. It &lt;strong&gt;guarantees the execution of specific code&lt;/strong&gt; that is required to run before the execution of other methods in the program like login function or age checking before vote casting function.&lt;/li&gt;     
&lt;/ul&gt; 
&lt;div class=&quot;div-green&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;Try to use the exit code in the finally block that doesn't need to be tested before execution.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; How Execution Flow in Try-Except-Finally Blocks?&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;As illustrated in the flow diagram, suppose you write a simple Python program in which you are &lt;em&gt;opening a database connection&lt;/em&gt;. During coding, you start from the &lt;strong&gt;try block&lt;/strong&gt; to handle if the error occurs beforehand. Now, if the compiler executes the program and gets an error instead. The compiler stops the execution, tries to resolve the exception first, and &lt;strong&gt;jumps to the except block&lt;/strong&gt;. If there is no error in the try block, the &lt;strong&gt;else block&lt;/strong&gt; will print the result. It ensures no error in the try block code because this block will only run when no exception is present. After that, the &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#finally-clause&quot; title=&quot;Else&quot;&gt;Finally&lt;/a&gt;&lt;strong&gt; is the code block &lt;/strong&gt;which will always get executed irrespective of whether you had an exception in your code or not. If you have opened a database connection it is essential to close those connections and the code for&lt;strong&gt; closing the connection&lt;/strong&gt; is written generally in the finally block regardless of exception otherwise you will run out of your connection pool.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=2186709608108625168&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;The &lt;strong&gt;else block code&lt;/strong&gt; depends on the try block code where the &lt;strong&gt;finally block&lt;/strong&gt; code is the concluding code.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Else Block Vs Finally Block&lt;/h2&gt; 
&lt;p&gt; &lt;/p&gt;&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Now, you are thinking about why you use the else block when you are using the finally block, both blocks are part of exception handling and are used after the try-except block, but each has its use case.&lt;/p&gt;  
&lt;ul&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; The &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#else&quot; title=&quot;exception handling&quot;&gt;Except&lt;/a&gt; block helps us by ensuring that the piece of code inside the block will &lt;strong&gt;execute only when there is no exception error&lt;/strong&gt; in the program.  If the exception is encountered in the try block, which is handled by the except block, then the compiler stops the executions there. But if the try block runs successfully without error, then else block will execute.&lt;/li&gt;  

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; The &lt;strong&gt;Finally block&lt;/strong&gt; helps us by ensuring that the piece of code inside the block &lt;strong&gt;will execute in any case&lt;/strong&gt;, &lt;strong&gt;regardless&lt;/strong&gt; of the &lt;strong&gt;exception encountered&lt;/strong&gt; in the program. It helps us to manage resources that are used during the program execution, i.e. closing database connections and files that would cause resource wastage and deadlock conditions. It is like using it for concluding a task at the end.&lt;/li&gt; 
&lt;/ul&gt;
&lt;div class=&quot;div-red&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;Remember, the code you put in else and finally block should be clean and does not cause any error. Otherwise, the exception is not caught in these block&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Code Demonstration: Finally Block&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; There are many ways of using the finally block for exception handling implementation in your Python program.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Finally Block Code: Without Exception Handling&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;print(&quot;SIMPLE CALCULATOR&quot;)  
print(&quot;Having operation '*' and '/'&quot;)  
def multiplication(num1, num2): #function for multiplication  
    return num1 * num2  
def division(num1, num2): #function for division  
    try:  
        num3 = num1 / num2 #this line will give exception if num2 values is zero  
        return num3  
    except ZeroDivisionError: #if this exception occurs, then the compiler jumps to this part   
        print(&quot;Error: you try to divide the number with 0&quot;)   
        return None  
    finally: 
        print(&quot;This is the end of Division Function&quot;) #run always when the code executes 
result = multiplication(8, 0)  
result1 = division(8, 8)  
print(&quot;Multiplication of two numbers:&quot; , result)  
print(&quot;Division of two numbers:&quot; , result1) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In the above code, I create two functions, i.e. for multiplication and division operations. Now in division operation when the user enters the value of the denominator. It will print the result of the calculation also the &lt;strong&gt;print line in the finally block&lt;/strong&gt; is also &lt;strong&gt;displayed on the terminal&lt;/strong&gt;. It's because whether an exception occurs or handles, it will print the line. Now you can test it by giving different values of denominators.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16740123373225469847&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Finally Block Code: With Exception Handling&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;print(&quot;SIMPLE CALCULATOR&quot;)  
print(&quot;Having operation '*' and '/'&quot;)  
def multiplication(num1, num2): #function for multiplication  
    return num1 * num2  
def division(num1, num2): #function for division  
    try:  
        num3 = num1 / num2 #this line will give exception if num2 values is zero  
        return num3  
    except ZeroDivisionError as e: #if this exception occurs then the compiler jumps to this part   
        print(&quot;Error: you try to divide the number with 0&quot;) 
        print(type(e)) #prints the exception class name  
        return None  
    finally: 
        print(&quot;This is the end of Division Function&quot;) #run always when the code executes 
result = multiplication(8, 5)  
result1 = division(8, 0)  
print(&quot;Multiplication of two numbers:&quot; , result)  
print(&quot;Division of two numbers:&quot; , result1)  
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In this code snippet, you can see that the exception occurs in the code as I am &lt;strong&gt;passing the value of the denominator as 0&lt;/strong&gt;. This raises the exception &lt;strong&gt;zero division error exception&lt;/strong&gt;. But if you look carefully at the output image, the &lt;strong&gt;finally block is still printing the line&lt;/strong&gt;. Regardless of the code with and without exception handling, this piece of code still displays the print statement.&lt;/p&gt; 
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17422744193459199356&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Finally Block Code: With Else Block&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;def read_file(file_path): 
    try: 
        with open(file_path, 'r') as file: 
            content =  file.readlines() 
    except FileNotFoundError as e: 
        print(&quot;Error: The file does not exist.&quot;) 
        print(type(e)) 
        return None 
    else: 
        print(&quot;There is no exception occur in the program&quot;) 
        return content 
    finally: 
        print(&quot;Finished processing the file.&quot;) 
        file.close() 
file_path = &quot;Content.txt&quot; 
content = read_file(file_path) 
print(&quot;The Content of file is&quot;, content) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In the above code as there is &lt;strong&gt;no exception&lt;/strong&gt; encountered the &lt;strong&gt;else block will also run with the finally block&lt;/strong&gt;. It will only run when there is no exception in the program, but it does not affect the execution of the finally block because whether the exception occurs or not the finally block will always run the code inside it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=5862910151719240977&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-faq&quot; style=&quot;margin-bottom: 15px; margin-top: 3px;&quot;&gt; 
&lt;span class=&quot;faq-header&quot; style=&quot;font-weight: bold; color: dark-gray;&quot;&gt;FAQs&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt; Q: Can I use try and finally block without except block? &lt;br&gt;A: Yes, you can because the except block is used for handling the exception and to catch the error in the try block so if you don't want to handle the error it does not affect the code of the finally block.&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt;Q: Can I have more than one finally block in the program?&lt;br&gt; A: Yes, if you want to use multiple finally blocks you can use it but make sure that each block code is clean and has a minimum chance of error.&lt;/span&gt; 
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Wrapping Up&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In this article, we talked about the &lt;strong&gt;&quot;Exception handling; Using Finally block&quot;&lt;/strong&gt; in Python. We saw examples with the help of coding that explain the purpose of the finally block other than a try-except block and see the difference in the finally and else blocks. Ultimately, you understand that the finally block has an &lt;strong&gt;important role in exception handling&lt;/strong&gt; as it is used for the &lt;strong&gt;implementation of concluding and finalizing code part&lt;/strong&gt; in the program. It will &lt;strong&gt;benefit&lt;/strong&gt; you with code &lt;strong&gt;cleanup operations and resource management&lt;/strong&gt; as well. Also, it runs the code in all circumstances to make it a robust and efficient application. If you understand the use of the finally block you will not only make your application error-prone but also manage the resources used in the program. Hope this guide is helpful for you. Happy Coding!&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Reference&lt;/h2&gt;   
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#finally&quot; title=&quot;Finally Block&quot;&gt; Finally Block in python &lt;/a&gt; &lt;/p&gt;
</description>
<category>File Handling</category>
<guid isPermaLink="true">https://coderlegion.com/186/python-opening-reading-files</guid>
<pubDate>Sat, 09 Mar 2024 02:25:03 +0000</pubDate>
</item>
<item>
<title>Python  Finally Block</title>
<link>https://coderlegion.com/185/python-finally-block</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Sometimes, when you are working in your program, a situation comes where &lt;strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/186/python-opening-%26-reading-files&quot; target=&quot;_blank&quot;&gt;file handling&lt;/a&gt; is used&lt;/strong&gt; for performing operations on the file. However, after completing the operation, you must &lt;strong&gt;close the file&lt;/strong&gt;. Also, when you use the &lt;strong&gt;database connection&lt;/strong&gt; in your program, the &lt;strong&gt;connection needs to be closed&lt;/strong&gt; after the task completion. Wondering &lt;em&gt;how you can achieve it&lt;/em&gt; by using exception handling? It is quite easy because you simply  put that code in the &lt;strong&gt;finally block&lt;/strong&gt; after the &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/164/python-try-except-blocks&quot; target=&quot;_blank&quot;&gt;try&lt;/a&gt; and &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/164/python-try-except-blocks&quot; target=&quot;_blank&quot;&gt;except&lt;/a&gt; block during your program development. In this article, I will cover the detailed overview of the finally block, when it is needed, its purpose, and some examples with the help of code. Let's get started.&lt;/p&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Finally Block in Python: An Overview&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In Python, the finally block is another key concept of exception handling after try and except block. This expression is used as &lt;strong&gt;code cleaning action&lt;/strong&gt; or &lt;strong&gt;logic cleaning&lt;/strong&gt; in programming, which means when you use the resource of a computer, you have to return it after achieving the result. Additionally, the finally block is &lt;strong&gt;utilized for resource management.&lt;/strong&gt; While working with try and except block, you put the piece of &lt;strong&gt;code in the finally block&lt;/strong&gt; that needs to be &lt;strong&gt;executed&lt;/strong&gt; regardless of an &lt;strong&gt;exception occurrence&lt;/strong&gt;.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Finally Block: Definition&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; The finally block in exception handling is the block used in &lt;strong&gt;conjunction with the try-except block&lt;/strong&gt;. It defines the piece-of-code that needs to be executed at the end, whether the exception occurs or not. The code written inside this block is used as a cleaning operation. It also ensures that whether the exception is encountered in the try block or handled in the except block, the finally block will always execute the code inside it.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Syntax for Finally Block&lt;/h3&gt;
&lt;pre&gt;  &lt;code&gt; 
try:   
#code that needs to be tested and can cause an exception   
pass   

except exception1:   
#code to handle the exception1   
pass 
   
finally: 
#code that needs to run whether exceptions occur or not 
pass 
&lt;/code&gt;  &lt;/pre&gt;  
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Purpose of Finally Block&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; The finally block has a very crucial role in programming language. It is not just a simple block that will &lt;strong&gt;execute whether errors occur or not&lt;/strong&gt;, but it will &lt;strong&gt;manage the code&lt;/strong&gt; and make the program robust. The purpose of the finally block in exception handling is:&lt;/p&gt; 
&lt;ul&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; It is used for cleanup activities when you are working in the program using the file. At the end, you can put the close file code in the finally block that &lt;strong&gt;ensures the resource is released&lt;/strong&gt; without creating any problems. Also, it ensures resource management like network connection and database connection closing that &lt;strong&gt;resolves&lt;/strong&gt; the issue of &lt;strong&gt;resource leak&lt;/strong&gt; and &lt;strong&gt;deadlock conditions.&lt;/strong&gt;&lt;/li&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; The code that is &lt;strong&gt;compulsory&lt;/strong&gt; to run regardless of &lt;strong&gt;exception occurrence or not&lt;/strong&gt; will also be achieved by using the finally block. It &lt;strong&gt;guarantees the execution of specific code&lt;/strong&gt; that is required to run before the execution of other methods in the program like login function or age checking before vote casting function.&lt;/li&gt;     
&lt;/ul&gt; 
&lt;div class=&quot;div-green&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;Try to use the exit code in the finally block that doesn't need to be tested before execution.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; How Execution Flow in Try-Except-Finally Blocks?&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;As illustrated in the flow diagram, suppose you write a simple Python program in which you are &lt;em&gt;opening a database connection&lt;/em&gt;. During coding, you start from the &lt;strong&gt;try block&lt;/strong&gt; to handle if the error occurs beforehand. Now, if the compiler executes the program and gets an error instead. The compiler stops the execution, tries to resolve the exception first, and &lt;strong&gt;jumps to the except block&lt;/strong&gt;. If there is no error in the try block, the &lt;strong&gt;else block&lt;/strong&gt; will print the result. It ensures no error in the try block code because this block will only run when no exception is present. After that, the &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#finally-clause&quot; title=&quot;Else&quot;&gt;Finally&lt;/a&gt;&lt;strong&gt; is the code block &lt;/strong&gt;which will always get executed irrespective of whether you had an exception in your code or not. If you have opened a database connection it is essential to close those connections and the code for&lt;strong&gt; closing the connection&lt;/strong&gt; is written generally in the finally block regardless of exception otherwise you will run out of your connection pool.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=2186709608108625168&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;The &lt;strong&gt;else block code&lt;/strong&gt; depends on the try block code where the &lt;strong&gt;finally block&lt;/strong&gt; code is the concluding code.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Else Block Vs Finally Block&lt;/h2&gt; 
&lt;p&gt; &lt;/p&gt;&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Now, you are thinking about why you use the else block when you are using the finally block, both blocks are part of exception handling and are used after the try-except block, but each has its use case.&lt;/p&gt;  
&lt;ul&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; The &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#else&quot; title=&quot;exception handling&quot;&gt;Except&lt;/a&gt; block helps us by ensuring that the piece of code inside the block will &lt;strong&gt;execute only when there is no exception error&lt;/strong&gt; in the program.  If the exception is encountered in the try block, which is handled by the except block, then the compiler stops the executions there. But if the try block runs successfully without error, then else block will execute.&lt;/li&gt;  

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; The &lt;strong&gt;Finally block&lt;/strong&gt; helps us by ensuring that the piece of code inside the block &lt;strong&gt;will execute in any case&lt;/strong&gt;, &lt;strong&gt;regardless&lt;/strong&gt; of the &lt;strong&gt;exception encountered&lt;/strong&gt; in the program. It helps us to manage resources that are used during the program execution, i.e. closing database connections and files that would cause resource wastage and deadlock conditions. It is like using it for concluding a task at the end.&lt;/li&gt; 
&lt;/ul&gt;
&lt;div class=&quot;div-red&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;Remember, the code you put in else and finally block should be clean and does not cause any error. Otherwise, the exception is not caught in these block&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Code Demonstration: Finally Block&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; There are many ways of using the finally block for exception handling implementation in your Python program.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Finally Block Code: Without Exception Handling&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;print(&quot;SIMPLE CALCULATOR&quot;)  
print(&quot;Having operation '*' and '/'&quot;)  
def multiplication(num1, num2): #function for multiplication  
    return num1 * num2  
def division(num1, num2): #function for division  
    try:  
        num3 = num1 / num2 #this line will give exception if num2 values is zero  
        return num3  
    except ZeroDivisionError: #if this exception occurs, then the compiler jumps to this part   
        print(&quot;Error: you try to divide the number with 0&quot;)   
        return None  
    finally: 
        print(&quot;This is the end of Division Function&quot;) #run always when the code executes 
result = multiplication(8, 0)  
result1 = division(8, 8)  
print(&quot;Multiplication of two numbers:&quot; , result)  
print(&quot;Division of two numbers:&quot; , result1) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In the above code, I create two functions, i.e. for multiplication and division operations. Now in division operation when the user enters the value of the denominator. It will print the result of the calculation also the &lt;strong&gt;print line in the finally block&lt;/strong&gt; is also &lt;strong&gt;displayed on the terminal&lt;/strong&gt;. It's because whether an exception occurs or handles, it will print the line. Now you can test it by giving different values of denominators.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16740123373225469847&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Finally Block Code: With Exception Handling&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;print(&quot;SIMPLE CALCULATOR&quot;)  
print(&quot;Having operation '*' and '/'&quot;)  
def multiplication(num1, num2): #function for multiplication  
    return num1 * num2  
def division(num1, num2): #function for division  
    try:  
        num3 = num1 / num2 #this line will give exception if num2 values is zero  
        return num3  
    except ZeroDivisionError as e: #if this exception occurs then the compiler jumps to this part   
        print(&quot;Error: you try to divide the number with 0&quot;) 
        print(type(e)) #prints the exception class name  
        return None  
    finally: 
        print(&quot;This is the end of Division Function&quot;) #run always when the code executes 
result = multiplication(8, 5)  
result1 = division(8, 0)  
print(&quot;Multiplication of two numbers:&quot; , result)  
print(&quot;Division of two numbers:&quot; , result1)  
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In this code snippet, you can see that the exception occurs in the code as I am &lt;strong&gt;passing the value of the denominator as 0&lt;/strong&gt;. This raises the exception &lt;strong&gt;zero division error exception&lt;/strong&gt;. But if you look carefully at the output image, the &lt;strong&gt;finally block is still printing the line&lt;/strong&gt;. Regardless of the code with and without exception handling, this piece of code still displays the print statement.&lt;/p&gt; 
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17422744193459199356&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Finally Block Code: With Else Block&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;def read_file(file_path): 
    try: 
        with open(file_path, 'r') as file: 
            content =  file.readlines() 
    except FileNotFoundError as e: 
        print(&quot;Error: The file does not exist.&quot;) 
        print(type(e)) 
        return None 
    else: 
        print(&quot;There is no exception occur in the program&quot;) 
        return content 
    finally: 
        print(&quot;Finished processing the file.&quot;) 
        file.close() 
file_path = &quot;Content.txt&quot; 
content = read_file(file_path) 
print(&quot;The Content of file is&quot;, content) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In the above code as there is &lt;strong&gt;no exception&lt;/strong&gt; encountered the &lt;strong&gt;else block will also run with the finally block&lt;/strong&gt;. It will only run when there is no exception in the program, but it does not affect the execution of the finally block because whether the exception occurs or not the finally block will always run the code inside it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=5862910151719240977&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-faq&quot; style=&quot;margin-bottom: 15px; margin-top: 3px;&quot;&gt; 
&lt;span class=&quot;faq-header&quot; style=&quot;font-weight: bold; color: dark-gray;&quot;&gt;FAQs&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt; Q: Can I use try and finally block without except block? &lt;br&gt;A: Yes, you can because the except block is used for &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/166/python-exception-handling&quot; target=&quot;_blank&quot;&gt;handling the exception&lt;/a&gt; and to catch the error in the try block so if you don't want to handle the error it does not affect the code of the finally block.&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt;Q: Can I have more than one finally block in the program?&lt;br&gt; A: Yes, if you want to use multiple finally blocks you can use it but make sure that each block code is clean and has a minimum chance of error.&lt;/span&gt; 
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Wrapping Up&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In this article, we talked about the &lt;strong&gt;&quot;Exception handling; Using Finally block&quot;&lt;/strong&gt; in Python. We saw examples with the help of coding that explain the purpose of the finally block other than a try-except block and see the difference in the finally and else blocks. Ultimately, you understand that the finally block has an &lt;strong&gt;important role in exception handling&lt;/strong&gt; as it is used for the &lt;strong&gt;implementation of concluding and finalizing code part&lt;/strong&gt; in the program. It will &lt;strong&gt;benefit&lt;/strong&gt; you with code &lt;strong&gt;cleanup operations and resource management&lt;/strong&gt; as well. Also, it runs the code in all circumstances to make it a robust and efficient application. If you understand the use of the finally block you will not only make your application error-prone but also manage the resources used in the program. Hope this guide is helpful for you. Happy Coding!&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Reference&lt;/h2&gt;   
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#finally&quot; title=&quot;Finally Block&quot;&gt; Finally Block in python &lt;/a&gt; &lt;/p&gt;
</description>
<category>Error Handling</category>
<guid isPermaLink="true">https://coderlegion.com/185/python-finally-block</guid>
<pubDate>Thu, 07 Mar 2024 21:46:45 +0000</pubDate>
</item>
<item>
<title>Python Try Except Blocks</title>
<link>https://coderlegion.com/164/python-try-except-blocks</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;After getting a detailed explanation of &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/166/python-exception-handling&quot; target=&quot;_blank&quot; title=&quot;Exception handling&quot;&gt;&lt;strong&gt;exception handling&lt;/strong&gt;&lt;/a&gt;, the next question that comes to your mind is how you can &lt;strong&gt;achieve&lt;/strong&gt; exception handling in your software program. Python has provided us with a very defined &lt;strong&gt;structured approach&lt;/strong&gt; related to exception handling, i.e. &lt;strong&gt;Try-Except block&lt;/strong&gt;. In this tutorial, I will cover the overview of the try-except statement, the workflow of try and except block, and a way to handle the exception with the help of different examples.&lt;/p&gt;  
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Try and Except Statement in Python: An Overview&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In Python, the try and except statement is the core concept that &lt;strong&gt;deals with incoming errors&lt;/strong&gt;. The Python developers implement the try and except block to &lt;strong&gt;catch the potential errors&lt;/strong&gt; that the program might encounter and take the correct measures on time before the application crashes. When you are working on a Python program, the &lt;strong&gt;piece of code having the potential risk&lt;/strong&gt; of encountering an error will be &lt;strong&gt;put inside the try block&lt;/strong&gt; later on, &lt;strong&gt;except block&lt;/strong&gt; is implemented to &lt;strong&gt;respond&lt;/strong&gt; to the related exception.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Try Block: Definition&lt;/h3&gt;  
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;When you use the &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#try&quot; title=&quot;Exception handling&quot;&gt;try&lt;/a&gt; block in your program, the &lt;strong&gt;compiler will test the code&lt;/strong&gt; throughout the execution. The code inside this block will run until an error is encountered or else gives the output.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Syntax for Try Block&lt;/h3&gt;  
&lt;pre&gt; 
&lt;code&gt; 
try:  
#code that needs to be tested and can cause an exception  
pass  
&lt;/code&gt; 
&lt;/pre&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Except Block: Definition&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#except&quot; title=&quot;Exception handling&quot;&gt;Except&lt;/a&gt; block is used to &lt;strong&gt;respond to the exceptions&lt;/strong&gt; coming in try block and deal with them. When the exception is encountered in a try block, the compiler jumps to the except block where the &lt;strong&gt;solution code is provided&lt;/strong&gt;. You define the except block in such a way that it will catch the error and handle it. Also, you can define as many except blocks as you need in the program.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Syntax for Except Block&lt;/h3&gt;  
&lt;pre&gt; 
&lt;code&gt; 
try:  
#code that needs to be tested and can cause an exception  
pass  

except exception1:  
#code to handle the exception1  
pass
  
except exception2:  
#code to handle the exception2  
pass  

except exceptionN:  
#code to handle the exceptionN  
pass 
&lt;/code&gt; 
&lt;/pre&gt; 
&lt;div class=&quot;div-blue&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;Remember, you can use multiple except blocks with a single try block.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; How does the Try-Except statement work?&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;As illustrated in the flow diagram, suppose you write a simple Python program where you are &lt;em&gt;adding two numbers&lt;/em&gt;. You take the number from the user where the user enters &lt;em&gt;&quot;a&quot;&lt;/em&gt; instead of number. During coding, you add this piece of code inside the try block to handle if an error comes beforehand. Now, the compiler executes the program and takes the number from the user to perform addition but &lt;strong&gt;gets an error&lt;/strong&gt; instead. Therefore, the compiler stops the execution, tries to resolve the exception first, and &lt;strong&gt;jumps to the except block that handles the exception&lt;/strong&gt;. Here, a typeerror exception occurs. If there is no error in the try block, the &lt;strong&gt;else block&lt;/strong&gt; will print the result. It ensures no error in the try block code because this block will only run when no exception is present.&lt;/p&gt; 
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16163686820856059913&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;You can use the try block without using the except block, but this is not a good approach and only be used when you don't want to address the exception at that time&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Code Demonstration: Try-Except Block&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;There are many &lt;strong&gt;ways&lt;/strong&gt; of using try and except blocks for exception handling implementation in your Python program.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Catching All Exception&lt;/h3&gt; 
&lt;ul&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;If you want to catch all the exceptions &lt;strong&gt;without specifying the exception name&lt;/strong&gt;, then the generic exception approach is used. This can be achieved by using the keyword, except &lt;strong&gt;without defining the exception type&lt;/strong&gt;. The compiler will catch all types of errors whenever it encounters the try block.&lt;/li&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;This approach is helpful when you want to catch all the exceptions without generically specifying the name and &lt;strong&gt;saves&lt;/strong&gt; your application from &lt;strong&gt;abrupt stopping&lt;/strong&gt; from unhandled exceptions.&lt;/li&gt; 

&lt;/ul&gt; 
&lt;div class=&quot;div-red&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt; In my opinion, always try to avoid using the &lt;strong&gt;catch-all exception&lt;/strong&gt; approach as it will also try to catch the debugging-related issues and hinder the code execution &lt;/span&gt;
&lt;/div&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Code for Catching All Exceptions&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;def addition(num1, num2): #addition function 
    try: 
        num3 = num1 + num2 #this line will raise exception 
    except Exception as e: 
        print(&quot;An Exception occur&quot;) #here the exception is handled
        print(type(e)) #prints the type of error with name
        return None 
    else: 
        return num3 
result = addition(&quot;8&quot;, 0) 
print(&quot;Addition of two numbers:&quot; , result) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In the above code, I define the addition function that takes two numbers as an argument and performs the addition operation. The variable &lt;strong&gt;num3&lt;/strong&gt; will store the result. I put the add operation and its result in the try block that raises the exception. After that, I write the except block with the &lt;strong&gt;base class Exception&lt;/strong&gt; that catches all the exceptions in the code and stores it in the variable e. The &lt;strong&gt;type(e)&lt;/strong&gt; will print the exception class with its name. To check, call the addition function and pass two values, one as string and the second as int, which raises the &lt;strong&gt;type error&lt;/strong&gt; you can see in the output.&lt;/p&gt; 
&lt;div class=&quot;div-green&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;Try to use &lt;strong&gt; except Exception as e&lt;/strong&gt; to get the details of the error&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt; &lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=11726072152280013535&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Catching Specific Exception&lt;/h3&gt; 
&lt;ul&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;The other way to catch the exceptions is by &lt;strong&gt;specifying the exception name&lt;/strong&gt;. This approach will help you handle the exception &lt;strong&gt;precisely and improve the program's robustness.&lt;/strong&gt;&lt;/li&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;This approach also ensures clarity in the program, as the handling code for each exception is defined separately.&lt;/li&gt; 

&lt;/ul&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Code for Catching Specific Exception&lt;/h3&gt;  
&lt;pre&gt;&lt;code&gt;def addition(num1, num2): 
    try: 
        num3 #here we are defining num3
        num = num1 + num2  #instead of using num3 we are using num that raises the exception
    except NameError: #catche the except and handles it
        print(&quot;Name Error: Your are trying to use undefined variable&quot;) 
        return None 
    else: 
        return num3 
result = addition(8, 0) 
print(&quot;Addition of two numbers:&quot; , result) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In the above code snippets, I defined the name of the exception as &lt;strong&gt;NameError in the except block&lt;/strong&gt;. When I am using the &lt;em&gt;num variable&lt;/em&gt; for storing the result, the variable &lt;strong&gt;num3&lt;/strong&gt; is undefined, which raises the error related to this exception. So, the compiler jumps to the except block and executes the code implemented here. You can also mention as many exceptions as possible that you think will be encountered.&lt;/p&gt; 
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt; &lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7985636732007505280&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Using the Try Except Block with Functions&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;You can also use the try and except block &lt;strong&gt;inside the function&lt;/strong&gt;, as I defined in the example of a simple calculator program at the coding part.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Code: Using Functions &lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;print(&quot;SIMPLE CALCULATOR&quot;) 
print(&quot;Having operation '-', '*' and '/'&quot;) 
def subtraction(num1, num2): #function for subtraction 
    try: 
        num3 = num1 - num2 #this line will give an exception if values are incorrect type 
        return num3 
    except TypeError: #here on getting exception compiler jumps into this part and executes the code   
        print(&quot;Error: you are giving string instead of integer number in Subtract Function&quot;) 
        return None 
def multiplication(num1, num2): #function for multiplication 
    return num1 * num2 
def division(num1, num2): #function for division 
    try: 
        num3 = num1 / num2 #this line will give exception if num2 values is zero 
        return num3 
    except ZeroDivisionError: #if this exception occurs then the compiler jumps at this part  
        print(&quot;Error: you try to divide the number with 0&quot;)  
        return None 
result1 = subtraction(&quot;10&quot;, 5) 
result2 = multiplication(5, 5) 
result3 = division(8, 0) 
print(&quot;Subtraction of two numbers:&quot; , result1) 
print(&quot;Multiplication of two numbers:&quot; , result2) 
print(&quot;Division of two numbers:&quot; , result3) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In the above program, I first created three &lt;a target=&quot;_blank&quot;&gt;functions&lt;/a&gt; related to each math operation. Each function will take two numbers as an argument and &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/180/python-return-statement&quot; target=&quot;_blank&quot;&gt;return&lt;/a&gt; the calculation to the result variable that prints the output. Here, I am using &lt;strong&gt;multiple try and except blocks&lt;/strong&gt; for each function. Firstly, in the &lt;em&gt;subtraction(num1, num2) function&lt;/em&gt;, the &lt;strong&gt;TypeError&lt;/strong&gt; exception is handled in the except block. Also, in the &lt;em&gt;division(num1, num2) function&lt;/em&gt;, I passed the values &lt;strong&gt;8 and 0&lt;/strong&gt;. As we know, the number cannot be divided by zero in practical math calculation, so as in programming, it creates the error by stopping the program abruptly. Therefore, except block is used to handle the &lt;strong&gt;ZeroDivisionError exception.&lt;/strong&gt; &lt;/p&gt; 
&lt;div class=&quot;div-green&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;In the try block, only add that piece of code that will raise the exception instead of adding all the code and trying to minimize the code of the try block&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt; &lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=4726703168562900301&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Propagate Exception&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;When you are working with the try-except block with a function, there is a situation needed when you &lt;strong&gt;call the function into another function&lt;/strong&gt; at that time. If the calling function &lt;strong&gt;causes an exception&lt;/strong&gt; and is not handled at the function definition, then the &lt;strong&gt;stack will propagate&lt;/strong&gt; to the top part where it is handled. Let's take an example of a division function.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Code: Implementing Propagating Exceptions&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;print(&quot;SIMPLE CALCULATOR&quot;) 
def division(num1, num2): #function for division 
        num3 = num1 / num2 #this line will give exception if num2 values is zero 
        return num3 
def calculation(num1, num2): 
    try: 
        result = division(num1,num2) #division function is call and stores the result 
        print(&quot;The Result of division of two numbers&quot; , result) 
    except ZeroDivisionError: #if this exception occurs then the compiler jumps at this part  
        print(&quot;Error: you try to divide the number with 0&quot;)  
        return None 
    print(&quot;calculation is done&quot;) 
calculation(8, 2) 
calculation(6,0) 
print(&quot;End&quot;) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;As depicted in the code, I created two functions named division(num1, num2) and calculation(num1,num2). The division(num1, num2) function will take the two variables to perform the division operation, store the result in the variable num3, and return it. After that, the &lt;em&gt;calculation(num1 ,num2) function&lt;/em&gt; is defined which calls the division(num1,num2) function and stores its result.  When you &lt;strong&gt;pass the values to the calculation(num1, num2) function&lt;/strong&gt;, it will jump to the division function for division operation, but if the &lt;strong&gt;num2 is zero&lt;/strong&gt; that will raise the exception. The exception is not handled there, so the &lt;strong&gt;compiler propagates to the calculation function&lt;/strong&gt; where it is handled.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt; &lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=11520254311896602287&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-faq&quot; style=&quot;margin-bottom: 15px; margin-top: 3px;&quot;&gt; 
&lt;span class=&quot;faq-header&quot; style=&quot;font-weight: bold; color: dark-gray;&quot;&gt;FAQs&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt; Q: Can I use try and except block within try and except block? &lt;br&gt;A: Yes, there is a concept of nested try-and-except block in Python through which you can define the nested try-except block in your program&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt;Q: Is it possible to catch all the exceptions? &lt;br&gt; A: Yes, if you want to catch all the exceptions at once then the approach of using the except keyword without specifying the name is essential because it will catch all the exception that comes in the program.&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px;&quot;&gt; Q: What is the use of the else block? &lt;br&gt; A: Using the else block within your program is a very good approach as it helps you to make sure that there are no exception encounters in your program.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Wrapping Up&lt;/h2&gt; 
&lt;p&gt; &lt;/p&gt;&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In conclusion, &lt;strong&gt;try and except block&lt;/strong&gt; is the fundamental topic of every programming language. It is the need for software programs because every programmer wants to write code that would be &lt;strong&gt;efficient and run smoothly&lt;/strong&gt;. These try and except blocks ensure that the program &lt;strong&gt;deals with the error gracefully&lt;/strong&gt; and &lt;strong&gt;doesn't perform the abnormal execution&lt;/strong&gt;. As we know, it is &lt;strong&gt;impossible&lt;/strong&gt; to find all the future errors beforehand, but with exception handling, you can &lt;strong&gt;prepare your program for future exceptions&lt;/strong&gt; to some extent. Now, I hope it will be easy for you to use exception handling with try and except statements in your code. Thanks for reading the guide. Happy Coding!&lt;/p&gt;
&lt;hr&gt;  
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Reference&lt;/h2&gt;  
&lt;ul&gt; 

&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#the-try-statement&quot; title=&quot;Try-Except Block&quot;&gt; Try-Except Block &lt;/a&gt;&lt;/li&gt; 

&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://pythonbasics.org/try-except/&quot; title=&quot;Exception handling&quot;&gt;Try and Except in Python&lt;/a&gt;&lt;/li&gt; 

&lt;/ul&gt; 
</description>
<category>Error Handling</category>
<guid isPermaLink="true">https://coderlegion.com/164/python-try-except-blocks</guid>
<pubDate>Mon, 04 Mar 2024 13:54:13 +0000</pubDate>
</item>
</channel>
</rss>