Error Handling in Python
As a programmer, one of the things you will encounter a lot in your career is errors. These errors, if not handled very well might cause problems from applications crashing to companies losing revenues as a result. Many programming languages have built-in methods to properly handle errors, and in this short article, we will be looking at different ways of handling errors in Python programming language.
Errors are issues that occur during the execution of a program. This will make the program or function to terminate abruptly. Syntax errors and exceptions are the two major types of errors. Syntax errors are the ones you are most likely to encounter due to some errors you introduce and would likely make your program not to run until you fix it. It can be something as minute as a missing semi-colon or a wrong indentation in python. Exceptions on the other mean your program is correct syntactically but is liable to encounter errors during execution.
Many times, we focus on functionalities in our code that we omit important things such as handling errors, which can find their way to the production environment and prove to be very costly. Users of your program or a QA engineer can enter a wrong input into your program, and if not handled properly, will crash your program.
Creating a bug-free application is impossible, and even large tech companies with some of the best engineers in the world fix bugs on their major products now and then. However, It is important to handle as many as possible errors that could crash your program before you release your application to the end-users.
We should learn to handle our program error gracefully so that we return a reasonable and human-readable message to the user, or simply log the error. We will be exploring the try-except — else — finally keywords in python. This is similar to try-catch-finally in many programming languages.
Let’s consider the following examples:
We create a simple function to add two numbers together.
def addNumbers(num1, num2):
result = num1+num2
print(f"Sum of num1 and num2 is : {result}")addNumbers(5,5)
out: Sum of num1 and num2 is : 10
Testing addNumber function with a string as num2.
addNumbers(5,'5')
out:
Traceback (most recent call last):
File "main.py", line 5, in <module>
addNumbers(5,'5')
File "main.py", line 2, in addNumbers
result = num1+num2
TypeError: unsupported operand type(s) for +: 'int' and 'str'
As seen in the above function, it will return the right result for a valid number but return a TypeError for the second test with string input. TypeError is one of the many types of builtin Errors in python, you can check python’s documentation to learn more Python Errors. To prevent the above function from crashing our application and return a meaningful response, we will need to introduce the try-except keyword.
def addNumbers(num1, num2):
try:
result = num1+num2
print(f"Sum of num1 and num2 is : {result}")
except:
print("Please enter a number.")addNumbers(5, '5')
out: Please enter a number.
Once an exception is detected during execution, the program jumps to the except block and executes the codes within the block. We can also add the else clause, which simply executes when no exceptions in the try block are raised.
def addNumbers(num1, num2):
try:
result = num1+num2
print(f"Sum of num1 and num2 is : {result}")
except:
print("Please enter a number.")
else:
print("All is well")addNumbers(5, 5)
out: Sum of num1 and num2 is : 10
All is well
Another way to handle an exception is to be specific about the exception type in the except section of the code or adding multiple exceptions with a single except clause. If we create a method to divide two numbers and we divide a number by zero, it will return a ZeroDivisionError. We can add multiple except clauses in our try…except statement.
def divideNumbers(num1, num2):
try:
result = num1/num2
print(f"Output is : {result}")
except TypeError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")divideNumbers(10, 2)divideNumbers(10, 0)out: Output is : 5.0
Cannot divide by zero.# Catching multiple exception with an except clause
# except TypeError | ZeroDivisionError: or
# except TypeError |ZeroDivisionError as err:
Error handling in python is much more than what we’ve covered so far, and I believe that you should check out the official python documentation to learn about other ways of handling exceptions/errors in python.
Happy learning!