Python Exception Handling: 5 Tricks You Didn’t Know

<p><strong>Custom Exceptions for Clearer Code</strong><br /> Instead of relying solely on Python&rsquo;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 &quot;Negative numbers are not allowed!&quot; def check_positive(number): if number &lt; 0: raise NegativeNumberError</pre> <p><strong>The Power of the&nbsp;</strong><code><strong>else</strong></code><strong>&nbsp;Clause in Exception Handling</strong><br /> Many (including me before I researched this article) are unaware of the&nbsp;<code>else</code>&nbsp;clause in exception handling. It runs when the&nbsp;<code>try</code>&nbsp;block doesn&#39;t raise any exceptions, making your code cleaner.</p> <pre> try: result = 10 / 2 except ZeroDivisionError: print(&quot;Can&#39;t divide by zero!&quot;) else: print(f&quot;Result is {result}&quot;)</pre> <p><strong>Using&nbsp;</strong><code><strong>logging</strong></code><strong>&nbsp;Over&nbsp;</strong><code><strong>print</strong></code><strong>&nbsp;for Exceptions</strong><br /> Instead of using&nbsp;<code>print</code>&nbsp;statements to display exceptions, use the&nbsp;<code>logging</code>&nbsp;module. It&#39;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&quot;An error occurred: {e}&quot;)</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&quot;An error occurred: {e}&quot;)</pre> <p><strong>Use&nbsp;</strong><code><strong>finally</strong></code><strong>&nbsp;for Cleanup Actions</strong><br /> The&nbsp;<code>finally</code>&nbsp;block runs regardless of whether an exception was raised. It&#39;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>