This article is a part of a 30 day Python challenge series. You can find the links to all the previous posts of this series here
- 30 Days of Python 👨💻 - Day One - Introduction
- 30 Days Of Python 👨💻 - Day 2 - Data Types I
- 30 Days of Python 👨💻 - Day 3 - Data Types II
- 30 Days Of Python 👨💻 - Day 4 - Data Types III
- 30 Days Of Python 👨💻 - Day 5 - Conditions And Loops I
- 30 Days Of Python 👨💻 - Day 6 - Loops II And Functions
- 30 Days Of Python 👨💻 - Day 7 - Developer Environment
- 30 Days Of Python 👨💻 - Day 8 - OOP Basics
- 30 Days Of Python 👨💻 - Day 9 - OOP Pillars
- 30 Days Of Python 👨💻 - Day 10 - OOP Missing Pieces
- 30 Days Of Python 👨💻 - Day 11 - Functional Programming
- 30 Days Of Python 👨💻 - Day 12 - Lambda Expression And Comprehensions
- 30 Days Of Python 👨💻 - Day 13 - Decorators
No program is perfect. Unless it is a hello world program written with great care 😃
Today I explored all about handling errors in Python, which I will try to explain in plain and simple words. Handling errors is probably the most important concepts of programming.
All applications are prone to errors a.k.a bugs or exceptions. Errors are not evil. Errors most of the time convey useful messages when a program fails to run or execute for whatever reason. It can be an accidental tying mistake, maybe the application is offline while it is trying to access the internet. Maybe there is an error while calculating, or maybe the program runs out of memory. There are a lot of possible errors that might happen when we write a program. When an error is detected, the program just terminates. This may or may not something we want. Rather than expecting code to run without errors, the better and more pragmatic approach is to handle errors and accordingly take some actions.
In Python, errors can be broadly segmented into two - Syntax Errors and Exceptions.
Syntax Errors occur when we write some Python code which the Python interpreter is unable to validate as correct Python code.
- print('A grave mistake) # Missing end quote. Will result in a syntax error
- def hello # Missing :, will result in syntax error
- print('hello')
Whenever we run into syntax errors, the Python interpreter does a very good job by providing in detail which line caused the error so it can be corrected.
The interesting part is about the other kind of error that might occur apart from a syntax error.
Our programs are often connect to the outside world to receive certain values and perform computations based on those values. There is always a probability that those values are not correct. In that case, an error would occur. Thus they need to be handled.
- age = input('Enter your age')
- if age > 18:
- print('You are an adult')
- else:
- print('You are a minor')
Running this simple code will result in an exception.
- Traceback (most recent call last):
- File "main.py", line 2, in <module>
- if age > 18:
- TypeError: '>' not supported between instances of 'str' and 'int'
The exception is a TypeError because the value of age is a string. So to prevent it, age needs to be type-casted or converted to an integer.
- age = int(input('Enter your age'))
- if age > 18:
- print('You are an adult')
- else:
- print('You are a minor')
Now, if the user provides a string value instead of a number, there will be another exception.
- Enter your age asdf
- Traceback (most recent call last):
- File "main.py", line 1, in <module>
- age = int(input('Enter your age'))
- ValueError: invalid literal for int() with base 10: 'asdf'
Try except block
To prevent such an error, Python provides a try except block, where the action is placed inside the try block and if there is an exception, the except block will be executed.
As a comparison, in the JavaScript universe, there is a try catch block. Python just has a different name for catch. The functionality is exactly the same.
- try:
- age = int(input('Enter your age'))
- if age > 18:
- print('You are an adult')
- else:
- print('You are a minor')
- except:
- print('Invalid value provided')
Else block
Besides the try except block, Python also provides an else block which gets executed if there is no exception in a try except block of code. It is an extension to the try except statement.
- try:
- age = int(input('Enter your age'))
- if age > 18:
- print('You are an adult')
- else:
- print('You are a minor')
- except:
- print('Invalid value provided')
- else:
- print('Thank You!')

Join the conversation! Your thoughts help the community grow.