diff --git a/tornado/concurrent.py b/tornado/concurrent.py
index 3c65d9a3..df12da87 100644
--- a/tornado/concurrent.py
+++ b/tornado/concurrent.py
@@ -33,6 +33,8 @@ import functools
 import sys
 import types
 
+from tornado.log import app_log
+
 import typing
 from typing import Any, Callable, Optional, Tuple, Union
 
@@ -185,6 +187,28 @@ def future_set_result_unless_cancelled(
         future.set_result(value)
 
 
+def future_set_exception_unless_cancelled(
+    future: Union["futures.Future[_T]", "Future[_T]"], exc: BaseException
+) -> None:
+    """Set the given ``exc`` as the `Future`'s exception.
+
+    If the Future is already canceled, logs the exception instead. If
+    this logging is not desired, the caller should explicitly check
+    the state of the Future and call Future.set_exception instead of
+    this wrapper.
+
+    Avoids asyncio.InvalidStateError when calling set_exception() on
+    a cancelled `asyncio.Future`.
+
+    .. versionadded:: 6.0
+
+    """
+    if not future.cancelled():
+        future.set_exception(exc)
+    else:
+        app_log.error("Exception after Future was cancelled", exc_info=exc)
+
+
 def future_set_exc_info(
     future: Union["futures.Future[_T]", "Future[_T]"],
     exc_info: Tuple[
@@ -193,19 +217,20 @@ def future_set_exc_info(
 ) -> None:
     """Set the given ``exc_info`` as the `Future`'s exception.
 
-    Understands both `asyncio.Future` and Tornado's extensions to
-    enable better tracebacks on Python 2.
+    Understands both `asyncio.Future` and the extensions in older
+    versions of Tornado to enable better tracebacks on Python 2.
 
     .. versionadded:: 5.0
+
+    .. versionchanged:: 6.0
+
+       If the future is already cancelled, this function is a no-op.
+       (previously asyncio.InvalidStateError would be raised)
+
     """
-    if hasattr(future, "set_exc_info"):
-        # Tornado's Future
-        future.set_exc_info(exc_info)  # type: ignore
-    else:
-        # asyncio.Future
-        if exc_info[1] is None:
-            raise Exception("future_set_exc_info called with no exception")
-        future.set_exception(exc_info[1])
+    if exc_info[1] is None:
+        raise Exception("future_set_exc_info called with no exception")
+    future_set_exception_unless_cancelled(future, exc_info[1])
 
 
 @typing.overload
diff --git a/tornado/httpclient.py b/tornado/httpclient.py
index d1c92a49..00df064f 100644
--- a/tornado/httpclient.py
+++ b/tornado/httpclient.py
@@ -45,7 +45,11 @@ import ssl
 import time
 import weakref
 
-from tornado.concurrent import Future, future_set_result_unless_cancelled
+from tornado.concurrent import (
+    Future,
+    future_set_result_unless_cancelled,
+    future_set_exception_unless_cancelled,
+)
 from tornado.escape import utf8, native_str
 from tornado import gen, httputil
 from tornado.ioloop import IOLoop
@@ -290,7 +294,7 @@ class AsyncHTTPClient(Configurable):
         def handle_response(response: "HTTPResponse") -> None:
             if response.error:
                 if raise_error or not response._error_is_response_code:
-                    future.set_exception(response.error)
+                    future_set_exception_unless_cancelled(future, response.error)
                     return
             future_set_result_unless_cancelled(future, response)
 
diff --git a/tornado/iostream.py b/tornado/iostream.py
index 2fd2814d..5e98e7fe 100644
--- a/tornado/iostream.py
+++ b/tornado/iostream.py
@@ -627,15 +627,17 @@ class BaseIOStream(object):
             futures.append(self._connect_future)
             self._connect_future = None
         for future in futures:
-            future.set_exception(StreamClosedError(real_error=self.error))
+            if not future.done():
+                future.set_exception(StreamClosedError(real_error=self.error))
             future.exception()
         if self._ssl_connect_future is not None:
             # _ssl_connect_future expects to see the real exception (typically
             # an ssl.SSLError), not just StreamClosedError.
-            if self.error is not None:
-                self._ssl_connect_future.set_exception(self.error)
-            else:
-                self._ssl_connect_future.set_exception(StreamClosedError())
+            if not self._ssl_connect_future.done():
+                if self.error is not None:
+                    self._ssl_connect_future.set_exception(self.error)
+                else:
+                    self._ssl_connect_future.set_exception(StreamClosedError())
             self._ssl_connect_future.exception()
             self._ssl_connect_future = None
         if self._close_callback is not None:
diff --git a/tornado/process.py b/tornado/process.py
index 51bb840c..c1a5fce7 100644
--- a/tornado/process.py
+++ b/tornado/process.py
@@ -27,7 +27,11 @@ import time
 
 from binascii import hexlify
 
-from tornado.concurrent import Future, future_set_result_unless_cancelled
+from tornado.concurrent import (
+    Future,
+    future_set_result_unless_cancelled,
+    future_set_exception_unless_cancelled,
+)
 from tornado import ioloop
 from tornado.iostream import PipeIOStream
 from tornado.log import gen_log
@@ -296,7 +300,9 @@ class Subprocess(object):
         def callback(ret: int) -> None:
             if ret != 0 and raise_error:
                 # Unfortunately we don't have the original args any more.
-                future.set_exception(CalledProcessError(ret, "unknown"))
+                future_set_exception_unless_cancelled(
+                    future, CalledProcessError(ret, "unknown")
+                )
             else:
                 future_set_result_unless_cancelled(future, ret)
 

InvalidStateError when cancelling http requests
I am using Tornado 5.1.1 with Python 3.6 asyncio.

When I cancel() an asyncio task holding a Tornado http fetch request, I get the following exception:

```
ERROR:tornado.application:Exception in callback functools.partial(<function wrap.<locals>.null_wrapper at 0x7fda5decba60>, HTTPResponse(_body=None,_error_i
Traceback (most recent call last):
File "/data/workspace/cape/attribute-pipeline/python/lib/python3.6/site-packages/tornado/ioloop.py", line 758, in _run_callback
ret = callback()
File "/data/workspace/cape/attribute-pipeline/python/lib/python3.6/site-packages/tornado/stack_context.py", line 300, in null_wrapper
return fn(*args, **kwargs)
File "/data/workspace/cape/attribute-pipeline/python/lib/python3.6/site-packages/tornado/httpclient.py", line 290, in handle_response
future.set_exception(response.error)
asyncio.base_futures.InvalidStateError: invalid state
```

The problem looks like it's here in `httpclient.py`:
```
        def handle_response(response):
            if raise_error and response.error:
                if isinstance(response.error, HTTPError):
                    response.error.response = response
                future.set_exception(response.error)
            else:
                if response.error and not response._error_is_response_code:
                    warnings.warn("raise_error=False will allow '%s' to be raised in the future" %
                                  response.error, DeprecationWarning)
                future_set_result_unless_cancelled(future, response)
        self.fetch_impl(request, handle_response)
        return future
```

For results Tornado uses the wrapper `future_set_result_unless_cancelled`.

For exceptions, Tornado just invokes `future.set_exception(response.error)` which triggers the invalid state error since the future has been cancelled externally:

https://github.com/tornadoweb/tornado/blob/master/tornado/httpclient.py#L293

Perhaps the set_exception() just needs a similar check-if-cancelled wrapper?
diff --git a/tornado/test/httpclient_test.py b/tornado/test/httpclient_test.py
index 0a732ddc..745a9cb1 100644
--- a/tornado/test/httpclient_test.py
+++ b/tornado/test/httpclient_test.py
@@ -23,7 +23,7 @@ from tornado.httpclient import (
 from tornado.httpserver import HTTPServer
 from tornado.ioloop import IOLoop
 from tornado.iostream import IOStream
-from tornado.log import gen_log
+from tornado.log import gen_log, app_log
 from tornado import netutil
 from tornado.testing import AsyncHTTPTestCase, bind_unused_port, gen_test, ExpectLog
 from tornado.test.util import skipOnTravis
@@ -570,6 +570,20 @@ X-XSS-Protection: 1;
         for k, v in response.time_info.items():
             self.assertTrue(0 <= v < 1.0, "time_info[%s] out of bounds: %s" % (k, v))
 
+    @gen_test
+    def test_error_after_cancel(self):
+        fut = self.http_client.fetch(self.get_url("/404"))
+        self.assertTrue(fut.cancel())
+        with ExpectLog(app_log, "Exception after Future was cancelled") as el:
+            # We can't wait on the cancelled Future any more, so just
+            # let the IOLoop run until the exception gets logged (or
+            # not, in which case we exit the loop and ExpectLog will
+            # raise).
+            for i in range(100):
+                yield gen.sleep(0.01)
+                if el.logged_stack:
+                    break
+
 
 class RequestProxyTest(unittest.TestCase):
     def test_request_set(self):

pip install -e .
parse_log_pytest
pytest
flake8 mypy black pytest coverage
apt-get update apt-get install -y gcc
3.6
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
black==22.8.0
certifi==2021.5.30
click==8.0.4
coverage==6.2
dataclasses==0.8
flake8==5.0.4
importlib-metadata==4.2.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mypy==0.971
mypy-extensions==1.0.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pathspec==0.9.0
platformdirs==2.4.0
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
-e git+https://github.com/tornadoweb/tornado.git@940fd87fe9145d1154c8457221f86d56ea063c65#egg=tornado
typed-ast==1.5.5
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work

name: tornado
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - attrs=21.4.0=pyhd3eb1b0_0
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - importlib_metadata=4.8.1=hd3eb1b0_0
  - iniconfig=1.1.1=pyhd3eb1b0_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - more-itertools=8.12.0=pyhd3eb1b0_0
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - packaging=21.3=pyhd3eb1b0_0
  - pip=21.2.2=py36h06a4308_0
  - pluggy=0.13.1=py36h06a4308_0
  - py=1.11.0=pyhd3eb1b0_0
  - pyparsing=3.0.4=pyhd3eb1b0_0
  - pytest=6.2.4=py36h06a4308_2
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - toml=0.10.2=pyhd3eb1b0_0
  - typing_extensions=4.1.1=pyh06a4308_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zipp=3.6.0=pyhd3eb1b0_0
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - black==22.8.0
      - click==8.0.4
      - coverage==6.2
      - dataclasses==0.8
      - flake8==5.0.4
      - importlib-metadata==4.2.0
      - mccabe==0.7.0
      - mypy==0.971
      - mypy-extensions==1.0.0
      - pathspec==0.9.0
      - platformdirs==2.4.0
      - pycodestyle==2.9.1
      - pyflakes==2.5.0
      - tomli==1.2.3
      - typed-ast==1.5.5
prefix: /opt/conda/envs/tornado

tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_error_after_cancel
tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_304_with_content_length tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_all_methods tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_basic_auth tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_basic_auth_explicit_mode tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_basic_auth_unicode tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_bind_source_ip tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_body_encoding tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_body_sanity_checks tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_chunked tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_chunked_close tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_configure_defaults tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_credentials_in_url tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_follow_redirect tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_future_http_error tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_future_http_error_no_raise tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_future_interface tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_callback tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_types tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_hello_world tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_multi_line_headers tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_non_ascii_header tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_patch_receives_payload tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_post tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_put_307 tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_response_times tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_reuse_request_from_response tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_streaming_callback tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_types tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_unsupported_auth_mode tornado/test/httpclient_test.py::RequestProxyTest::test_bad_attribute tornado/test/httpclient_test.py::RequestProxyTest::test_both_set tornado/test/httpclient_test.py::RequestProxyTest::test_default_set tornado/test/httpclient_test.py::RequestProxyTest::test_defaults_none tornado/test/httpclient_test.py::RequestProxyTest::test_neither_set tornado/test/httpclient_test.py::RequestProxyTest::test_request_set tornado/test/httpclient_test.py::HTTPResponseTestCase::test_str tornado/test/httpclient_test.py::SyncHTTPClientTest::test_sync_client tornado/test/httpclient_test.py::SyncHTTPClientTest::test_sync_client_error tornado/test/httpclient_test.py::HTTPRequestTestCase::test_body tornado/test/httpclient_test.py::HTTPRequestTestCase::test_body_setter tornado/test/httpclient_test.py::HTTPRequestTestCase::test_headers tornado/test/httpclient_test.py::HTTPRequestTestCase::test_headers_setter tornado/test/httpclient_test.py::HTTPRequestTestCase::test_if_modified_since tornado/test/httpclient_test.py::HTTPRequestTestCase::test_null_headers_setter tornado/test/httpclient_test.py::HTTPErrorTestCase::test_copy tornado/test/httpclient_test.py::HTTPErrorTestCase::test_error_with_response tornado/test/httpclient_test.py::HTTPErrorTestCase::test_plain_error
tornado/iostream.py tornado/concurrent.py tornado/httpclient.py tornado/process.py
tornado/iostream.py tornado/concurrent.py tornado/httpclient.py tornado/process.py