# Catch OpenCV Python Exception

**URL:** <https://forum.opencv.org/t/catch-opencv-python-exception/1848>\
**Category:** Python\
**Tags:** videoio\
**Created:** [February 26, 2021, 9:13pm UTC](https://forum.opencv.org/t/catch-opencv-python-exception/1848 "2021-02-26T21:13:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![phriskiii](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/phriskiii/32/689_2.png) [@phriskiii](https://forum.opencv.org/u/phriskiii)\
**Post date:** [February 26, 2021, 9:13pm UTC](https://forum.opencv.org/t/catch-opencv-python-exception/1848/1 "2021-02-26T21:13:53Z")

</div>

I have written a simple motion capture and recording script in Python 3. I am on cv2 version 4.4.0, installed on Ubuntu using “apt install python3-opencv”. My script connects to an IP camera, fetching the URL from a config file. When a host at a URL isn’t reachable, I raise an exception, output a message on the command line, and wait 30 seconds. However, even when catching this error, OpenCV spits out an error on the terminal. I really don’t want to see this error, as I want the terminal to be a clean experience for the user. How can I successfully catch and suppress this error message?

My full code is here on [Github](https://github.com/paulrisk3/picam-motion-detection/blob/master/opencv-server.py).

```auto
while True:
      try:
          video=cv2.VideoCapture(camera_url)
          if video is None or not video.isOpened():
            raise ConnectionError
          size=(int(video.get(3)), int(video.get(4)))
          check, frame = video.read()

...

except ConnectionError:
          print("Retrying connection to ",camera_name," in ",str(reconnect_time), " seconds...")
          time.sleep(reconnect_time)

```

The error message I would like:

```auto
Retrying connection to front_yard in 30 seconds...

```

The error message I get:

```auto
[tcp @ 0x18d4b40] Connection to tcp://192.168.1.102:8000 failed: No route to host
[ERROR:0] global /tmp/pip-req-build-99ib2vsi/opencv/modules/videoio/src/cap.cpp (140) open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.4.0) /tmp/pip-req-build-99ib2vsi/opencv/modules/videoio/src/cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): http://192.168.1.102:8000/stream.mjpg in function 'icvExtractPattern'

Retrying connection to front_yard in 30 seconds...

```

---

<div class="post-metadata">

**Author:** ![crackwitz](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/crackwitz/32/14_2.png) [@crackwitz](https://forum.opencv.org/u/crackwitz)\
**Post date:** [February 26, 2021, 9:21pm UTC](https://forum.opencv.org/t/catch-opencv-python-exception/1848/2 "2021-02-26T21:21:30Z")

</div>

create the VideoCapture with `apiPreference=cv2.CAP_FFMPEG` or something similar. then the backend is fixed and no automatic choice has to happen (that’s what you see going on).
