Python Exception Handling: 5 Tricks You Didn’t Know
<p><strong>Custom Exceptions for Clearer Code</strong><br />
Instead of relying solely on Python’s built-in exceptions, create custom ones for specific scenarios in your application. This makes your code more readable and provides descriptive error messages.</p>
<pre>
class NegativeNumberError(Exception):
def __str__(self):
return "Negative numbers are not allowed!"
def check_positive(number):
if number < 0:
raise NegativeNumberError</pre>
<p><strong>The Power of the </strong><code><strong>else</strong></code><strong> Clause in Exception Handling</strong><br />
Many (including me before I researched this article) are unaware of the <code>else</code> clause in exception handling. It runs when the <code>try</code> block doesn't raise any exceptions, making your code cleaner.</p>
<pre>
try:
result = 10 / 2
except ZeroDivisionError:
print("Can't divide by zero!")
else:
print(f"Result is {result}")</pre>
<p><strong>Using </strong><code><strong>logging</strong></code><strong> Over </strong><code><strong>print</strong></code><strong> for Exceptions</strong><br />
Instead of using <code>print</code> statements to display exceptions, use the <code>logging</code> module. It's more versatile, allowing you to store error messages in files or other output streams.</p>
<pre>
import logging
logging.basicConfig(level=logging.ERROR)
try:
# some code
except Exception as e:
logging.error(f"An error occurred: {e}")</pre>
<p><strong>Catch Multiple Exceptions in One Line</strong><br />
If you have multiple exceptions that need similar handling, catch them in a single line to make your code neater.</p>
<pre>
try:
# some code
except (ValueError, TypeError, IndexError) as e:
print(f"An error occurred: {e}")</pre>
<p><strong>Use </strong><code><strong>finally</strong></code><strong> for Cleanup Actions</strong><br />
The <code>finally</code> block runs regardless of whether an exception was raised. It's perfect for cleanup actions, like closing files or releasing resources.</p>
<p><a href="https://levelup.gitconnected.com/python-exception-handling-5-tricks-you-didnt-know-d7b4324e93a6">Website</a></p>