Member-only story
3 Ways To Improve Your Try/Except Statements in Python
Tips to ensure effective exception handling

Try and except statements are one of the first tools one is introduced to when learning Python. They enable users to test code for errors and handle exceptions.
Unfortunately, it is easy for people to write try and except clauses in ways that either don’t yield the most benefit or end up causing a lot of trouble for them in the long run.
Here, we go over three things users can do to write effective try/except statements in Python:
1. Avoid Using The Pass Statement
Let’s start by addressing one of the more egregious mistakes one can make when using try/except statements: including a pass statement in the except clause.
The pass statement serves as a placeholder, which does have its uses in certain scenarios. However, the one place it does not belong is in the except clause.
To illustrate why this is the case, let’s write code that tries to divide two numbers inputted by the user where a pass statement is inserted into the except clause.
The code might look benign at face value. After all, it will run without issue. However, if the division is unsuccessful and raises an exception, we would be completely unaware.
In general, this can pose an issue as the outcome of a try/except statement can impact subsequent operations. If the division is important in the Python script, we need to know when that value is or isn’t obtained.
For that reason, it is a good practice to track when the except clause is triggered.
We can improve the previous code by replacing the pass statement with a print statement. This way, we will know when the division can or can not be executed.