How to raise an exception in Python – when to use exception handling
An exception is an unexpected event that affects the normal execution of program instructions.
Exceptions can also be referred to as Logical errors that occur at runtime and are different from syntax errors. So an exception is simply a situation that makes the compiler throw an error at runtime.
In order to continue with the normal program execution, we need to handle these exceptions.
Exception types – How to raise an exception in Python
There are two types of exceptions in Python. Apart from built-in exceptions, we can also directly or indirectly derive custom exceptions from the Exception class.
Exceptions may occur when we try to perform operations such as trying to read a file that does not exist or when we try to divide a number by zero. Such operations result in FileNotFoundError and DivisionByZeroError respectively.
How to raise an exception in Python – Examples
In this article, we are going to explore some of the basic ones. For instance, we’re going to explore what happens when we try to add a number to a string.
We have run into a TypeError since we cannot concatenate or add a string and number together.
Exception handling within a try-except block
Using a try and except block, we can handle exceptions so that our program does not crash when such an error occurs.
If an exception occurs the except block is executed. However, if no execution occurs the except block is skipped and instead, the try block is executed.
In the prior example, we already know that an error will occur since we understand that we can only concatenate a string to a string.
Checking errors at runtime
However, we can also use the try clause to check for the possibility that an error may occur in a block of code at runtime.
In the example below we have put the operation that is likely to raise an exception at runtime under the try block.
And under the except block, we can choose to have any code that we want to be executed when an exception occurs. In this case, it is just a simple print statement.
The above program will be able to capture all exceptions and handle them in the same way since we have not mentioned any specific exceptions.
How to raise an exception in Python – Using specific exceptions
It is not considered a good practice to catch all exceptions, we should instead specify the specific exception that every except clause should handle.
In this case, the exception that we are hoping to handle is the TypeError, we are also going to alias this exception with a common name such as err. This allows us to access the exception using a common name.
Validate user input within the except block
In this case, we have used the alias of the exception to just print out the actual text of the error. However, generally speaking, you may want to do something else under the except block for example we could validate some user input.
On the other hand, if no error occurred then the try block will be executed as shown below.
The “raise” keyword
Exceptions are raised when errors occur at runtime, however, we can also manually raise exceptions using the raise keyword. This will return an error message and also stop our program from further executing.
Therefore this means that we have an opportunity to perform some operations before we can raise an exception. For example, we can perform some logging before raising an exception that will stop our program.
Summary
This is how to raise an exception in Python. 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.
