Back to Blog
Python try except5/18/2023 ![]() ![]() ![]() Then, what if there are more possible exceptions? Rather than adding more and more conditions in the list comprehension, I believe using suppress is more elegant.Īdditionally, what if you have more than 2 possible exceptions? Or, let’s say you don’t care what is the exception, just want to bypass it whenever it happens. Or, with the suppress function, you just add another exception type: for num in nums: with suppress(ZeroDivisionError, TypeError): result += 1/num 2) If there is no exception, the clause of except will be bypassed and the try statement. You could also handle it in the above way: result = sum() How python 3 try-except works 1) First, the try clause is executed. Please note that there is a string ‘3’ at the second last position. For example, what if the list is like this: nums = But I think the value of the suppress function exists in other scenarios. My example isn’t perfect, because it is indeed more preferable to be fixed by the above solution rather than using suppress function. In this article, I just wanted to create such a scenario that I can demonstrate suppress. In the question, I was asked why not fix it as follows: result = sum() The short answer is: No, you don’t have to use it. This section is updated based on a question from response. How to use try and except in Python to catch exceptions To catch a Python exception, use a try statement. So, with the suppress function, the exception that passed in as a parameter will be ignored. Isn’t that more concise and intuitive? It is more “Pythonic” too, in my opinion. ![]()
0 Comments
Read More
Leave a Reply. |