STM32 USB CDC: How to stop device transmitting via USB when not connected
At the lowest level, the USB host polls the device to check for available data.

From the device, it is not possible to determine whether the host is just busy and will continue receiving data later, or whether there is no application that has opened the serial device.

If you have the ability to cancel a transmit packet, you could implement a timeout.
Otherwise, you have to stop what you're doing, and wait until the package actually got transmitted.