How to throw an exception in Python
An exception is an unusual or unexpected occurrence within a program that interrupts the normal flow of the program.
There are quite a number of built-in exceptions in Python that are often raised depending on the type of error encountered within the program.
Why is it important to handle exceptions?
Unhandled exceptions in a program eventually lead to the programs crashing with an error message displayed in the terminal.
Therefore, when developing applications that will eventually be used by many users we need to ensure that all exceptions are handled.
How to handle exceptions?
In this article, we are going to explore how exceptions come about and how we can handle them.
In the example below we have a simple function that takes in three numbers as parameters and adds them together and returns the value.
Using the add() function
Now suppose we intentionally pass a string as one of the arguments when calling the add() function.
Obviously, this will lead to an error since the addition operator can only be used to find the sum of numeric types; integers in this case.
Using try-except blocks
In Python, exceptions are best handled using the try and except clauses. We are going to place the part of our program that could potentially lead to an error under the try clause. The except clause on the other hand is going to handle the exception if it occurs.
Therefore under the exception block, we can write any code that we would want to be executed when an error occurs within the program.
How to throw an exception in Python – Using the “pass” statement
In the code below we have used the pass statement as a placeholder, therefore nothing will be executed if an exception occurs in our program.
In the Python program above no exception occurs therefore the code under the try block is executed successfully. In addition, the last print statement is also executed as a result we have two sixes printed out.
Pass statement in practice
However, if an error occurs the code under the try clause will not be executed, instead, the except clause is invoked.
Since we only have a pass statement under the except block nothing really happens. In this case, only the last print statement will be executed thus we only get one six printed.
How to throw an exception in Python – Specific exception types
While this method works, it is not the ideal way of handling exceptions in Python. It is considered a good practice when we specify the exact exception that the except clause should handle.
This allows us to catch exact exceptions and also get a precise error message. Please note that we can also alias exceptions allowing us to access their attributes using common names as we have done below.
In the example above we have successfully handled the TypeError exceptions returning a precise message. We can also note that the last print statement was still executed.
How to throw an exception in Python – Using the “raise” keyword
Now if we wish to stop the program from executing any further statements that come after this try and except block then we can use the raise keyword.
The raise keyword allows us to manually throw an exception, print a detailed error message and also stop any further program execution.
When writing production-ready code exceptions would normally be logged and stored somewhere where one can easily access and retrieve them.
The raise statement is really useful when we are uncertain about the type of Exception that we are expecting in our code. In such a case the raise keyword returns a detailed error message that we can refer to.
Summary
This is how to throw an exception in Python in practice. If you’d like to see more programming tutorials, check out our Youtube channel, where we have plenty of Python video tutorials in English.
In our Python Programming Tutorials series, you’ll find useful materials which will help you improve your programming skills and speed up the learning process.
Programming tutorials
- How to use the Python for loop
- How to use Python Sets
- How to use a Python Dictionary
- How to use Python Classes
- How to use Python Range
- How to use Python if-else statements
- How to use Python RegEx
- How to use Python Lists
- How to use Python Enumerate
- How to use Python Functions
- How to use Python Split
- How to use Python Try-Except
- How to use Python Tuples
- How to use Python Arrays
- How to use Python Sort
- How to use the Python DateTime
- How to download Python?
- How to use the Python FileWrite function
- How to use Python Lambda
- How to use Python ListAppend
- How to use Python ListComprehension
- How to use Python Map
- How to use Python Operators
- How to use Python Pandas
- How to use Python Requests
- How to use Python Strings
- How to use Python Count
- How to use Python Comments
- How to use the Python File Reader method
- How to use the Python IDE-s
- How to use Python logging
- How to use Python Print
- How to use the Python Zip
- How to use Python Append
- How to use Python Global Variables
- How to use the Python join method
- How to use Python list length
- How to use Python JSON files
- How to use Python Modulo
- How to use Python file opening methods
- How to use Python round
- How to use Python sleep
- How to use Python replace
- How to use Python strip
- How to use the Python Time module
- How to use Python unittests
- How to save data to a text file using Context Manager?
- How to use Python external modules
- How to use Python find
- How to install the Python pip package manager
- How to delete files in Python
- Parsing XML files in Python
- How to make a GUI in Python
- How to use Python in Command Prompt
- How to Run a Python Program in VS Code
- How to run a program in Python IDLE
- How to run a program in Jupyter Notebook
- How to read a text file in Python
- How to add numbers in Python
- How to ask for user input in Python
- How to debug in Python
- How to create a thread in Python
- How to end a program in Python
- How to import a library in Python
- How to use the PIP package manager
- How to use classes in Python
- How to reverse strings in Python
- How to convert a string to int in Python
- How to print on the same line in Python
- How to remove items from a list
- How to add to a dictionary in Python
- How to raise an exception in Python
- How to throw an exception in Python
- How to stop a program in Python
- How to use Python assert
- How to use the Python compiler
Would you like to learn how to code, online? Come and try our first 25 lessons for free at the CodeBerry Programming School.
Learn to code and change your career!

100% ONLINE

IDEAL FOR BEGINNERS

SUPPORTIVE COMMUNITY

SELF-PACED LEARNING
Not sure if programming is for you? With CodeBerry you’ll like it.
