<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged exception</title>
<link>https://coderlegion.com/tag/exception</link>
<description>Powered by Question2Answer</description>
<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>