Python Lessons – 4.4 Raise an exception

Python Lessons - 4.4 Raise an exception

Raising Exceptions

You have seen that exceptions happen when you have some type of error detected by the system during the execution of the code. Sometimes it may happen that we ourselves want to create and throw an exception. The reasons for doing this can be many.

Often you might want to create a more specific exception, which signals a specific mistake to who in the future is using our code. For example, we are developing code that analyzes images captured by a WebCam and we want to create an ImageTooDark exception to signal who is using our code that the image to be processed is too dark.

Another case could be to take a generic exception and subdivide it into more specific exceptions, which can then be managed differently depending on the various cases.

To raise an exception use the raise clause.

raise ExceptionName

Also you can throw an exception with argument the specific error message

raise ExceptionName(“details about error”)

Existing exceptions can be launched,

b = input("Insert a number ")
b = int(b)
if b < 0:
    raise ValueError("Negative value")

Executing the code results in an exception

Insert a number: -3
Traceback (most recent call last):
File "C:/Python34/", line 4, in
raise ValueError("Negative value")
ValueError: Negative value 

Or use new ones. To define a new exception it is necessary to use the definition of classes (we’ll see how to do it later, for now only copy the code). Once you define a new exception, we can launch it with the raise clause. When managing our exception (whether we will do it, or someone else will do it) it will be possible to print the message directly using the value attribute that we have defined within the class.

class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
b = input("Insert a number: ")
    b = int(b)
    if b < 0:
        raise MyError("Negative Value")
except MyError as e:

In fact in this case the message is displayed following the launch (and management) of the MyError exception.

Insert a number: -3
Negative value

⇐ Go to Python Lesson 4.3 – Raise

Go to Python Lesson 4.5  – Asserts ⇒

Leave a Reply