How to raise an exception in Python – with example

  • Reading time:15 mins read

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

 

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. 

 

How to raise an exception in Python

 

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.

 

How to raise an exception in Python

 

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

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.