Raising a TimeoutExpired Error
00:00
So far we have seen two types of error. The first type of error is when we used, instead of Python, we used a program that doesn’t exist. In my case, it was pyth
and that resulted in a FileNotFoundError
.
00:14
The second type of error is when we called a process here, or you know, a program that doesn’t exist. I used simple_timer
without the .py
and that then creates a, or results in a CalledProcessError
.
00:28
Now the third type of error is when Python exists and simple_timer.py
exists, but the process just keeps running forever because of an infinite loop or whatever the problem with the code may be.
00:41
So to stop that from happening, you can add another argument here, which is called timeout
. And in my case, I’m going to set that equal to say three seconds.
00:51
Now I know my timer runs for five seconds. If I set my timeout
to three, then it should stop after three seconds and go your process takes too long.
01:00 Of course, it doesn’t know that my process is supposed to take five seconds, but I’m just trying to make a point here. So it starts for five seconds and after three seconds, there you go.
01:10 You get a whole lot of gobbledygook and here at the end it says there is, or it raises a timeout error and the timeout happens after, well almost three seconds.
01:22
So that is the timeout error. Now as a final note, for the timeout error to come up, you don’t actually need check=True
. So if a run is like this, you will get the same thing after three seconds.
01:35
The TimeoutExpired
error is raised.
01:39 As a final point, let me run you through an example of how you can handle these subprocess exceptions in real life.
01:48
The way to usually deal with exceptions is to use the try
except
structure. So I have an example on screen here in case you don’t know how that works. So you have a certain functionality you like to test.
02:01
You put that within try
. If it does not give you an error, it will run it, but if it does give you an error, it will then look at what kind of error you get and it will then execute the except
parts of the code depending on which error you get.
02:16
So we ran into a FileNotFoundError
, a CalledProcessError
, and a TimeoutExpired
error. And this is what will happen in those cases.
02:27 It will print the statements accordingly.
02:31 In the next lesson, we’re going to move to the next level really when we talk about communication with processes.
Become a Member to join the conversation.