Writing Better Python Code: How to Handle Exceptions for Better Code Quality and Reliability
In Python, exceptions are raised when an error occurs during the execution of a program. Exception handling is an essential part of writing robust Python code. It allows our program to respond gracefully to unexpected situations that might occur during runtime.
Like everything, there is a good way and not-so-good ways to do exception handling in Python. Using a bare except statement is one of the not-so-good ways to do exception handling.
What are Bare Exception Handlers?
In Python, a bare exception handler is one that does not specify the type of exception it's meant to handle. This means it catches all exceptions indiscriminately, even those that we may not expect or intend to catch, such as SystemExit and KeyboardInterrupt exceptions.
try:
...
except:
...
The problem with Bare Exception Handling
Consider the following code, if the user hits Ctrl+C while the program is running, a KeyboardInterrupt exception will be raised. However, since we are using a bare except statement, the KeyboardInterrupt will be caught and the program will print "Not a number. Try again!" instead of terminating the program as expected.
while True:
try:
s = input('Input a number:')
x = int(s)
except:
print('Not a number, Try again!')
Specify the type of error we expect
Instead of using a generic Exception to handle the error, we should handle the specific ValueError exception, which is raised when the input cannot be converted to an integer.
while True:
try:
s = input('Input a number:')
x = int(s)
except ValueError:
print('Not a number, try again!')
Another example
import requests
try:
response = requests.get('https://non_existent_website.com')
print(response.text)
except:
print('An error occurred.')
This script will print "An error occurred" for any exception, whether it's a ConnectionError because the website doesn't exist, or a TimeoutError because the request took too long. It's not clear what the actual problem is, making it harder to fix.
import requests
try:
response = requests.get('https://non_existent_website.com')
print(response.text)
except requests.exceptions.ConnectionError:
print('Could not connect to website.')
except requests.exceptions.Timeout:
print('Request timed out.')
Post a Comment