Hidden Functionality of Try and Accept Blocks in Python
<p>If you code in Python than, you have probably already worked with a lot of <code>try</code> and <code>except</code> blocks. In this blog, we will explore some of the hidden functionality of these blocks. We will demonstrate this by creating a function called <code>divide</code>, which divides <code>a</code> by <code>b</code> and returns a string. We will handle two specific exceptions: <code>ZeroDivisionError</code> if the user divides by zero, and <code>TypeError</code> if they enter a non-numeric value. Let's run the program to test it out.</p>
<pre>
def divide(a, b):
try:
result = a / b
return str(result)
except ZeroDivisionError:
return "Error: Division by zero"
except TypeError:
return "Error: Invalid input"
print(divide(10, 4)) # Output: 2.5
print(divide(10, 'a')) # Output: Error: Invalid input
print(divide(10, 0)) # Output: Error: Division by zero</pre>
<h1>Hidden Functionality: <code>else</code> Block</h1>
<p>Now, let’s explore the <code>else</code> block in a <code>try</code> and <code>except</code> block. If the code in the <code>try</code> block runs successfully without encountering any exceptions, everything in the <code>else</code> block will be executed. This provides an opportunity to add additional functionality. For example, we can print a success message. Let's modify our code to include the <code>else</code> block.</p>
<p><a href="https://python.plainenglish.io/hidden-functionality-of-try-and-accept-blocks-in-python-e28b32fea2ea">Read More</a></p>