pep8speaks: Hello @mrbean-bremen! Thanks for submitting the PR.

 - There are no PEP8 issues in the file [`pydicom/filewriter.py`](https://github.com/mrbean-bremen/pydicom/blob/e8a8fede5dcf0de023e25729eaca808dac1e452e/pydicom/filewriter.py) !

 - There are no PEP8 issues in the file [`pydicom/tests/test_filewriter.py`](https://github.com/mrbean-bremen/pydicom/blob/e8a8fede5dcf0de023e25729eaca808dac1e452e/pydicom/tests/test_filewriter.py) !


mrbean-bremen: Hm, some of the tests fail consistently - also in master. I have no idea what happens...
mrbean-bremen: The failing builds are unrelated - I created a separate issue for that. 
darcymason: Forgot about this one ... merging now.
diff --git a/doc/whatsnew/v1.3.0.rst b/doc/whatsnew/v1.3.0.rst
index 029b08933..28cee247f 100644
--- a/doc/whatsnew/v1.3.0.rst
+++ b/doc/whatsnew/v1.3.0.rst
@@ -15,5 +15,7 @@ Enhancements
 Fixes
 .....
 
+* Raise exception with specific message if value is too large to be written
+  in explicit transfer syntax (:issue:`757`)
 * Do not derive `Dataset` from `dict` - fixes behavior in newer Python versions
-  (:issue:`765`)
\ No newline at end of file
+  (:issue:`765`)
diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py
index ae045069b..f3b8c04c7 100644
--- a/pydicom/filewriter.py
+++ b/pydicom/filewriter.py
@@ -2,6 +2,8 @@
 """Functions related to writing DICOM data."""
 
 from __future__ import absolute_import
+
+import struct
 from struct import pack
 
 from pydicom import compat
@@ -484,7 +486,16 @@ def write_data_element(fp, data_element, encodings=None):
     value_length = buffer.tell()
     if (not fp.is_implicit_VR and VR not in extra_length_VRs and
             not is_undefined_length):
-        fp.write_US(value_length)  # Explicit VR length field is only 2 bytes
+        try:
+            fp.write_US(value_length)  # Explicit VR length field is 2 bytes
+        except struct.error:
+            msg = ('The value for the data element {} exceeds the size '
+                   'of 64 kByte and cannot be written in an explicit transfer '
+                   'syntax. You can save it using Implicit Little Endian '
+                   'transfer syntax, or you have to truncate the value to not '
+                   'exceed the maximum size of 64 kByte.'
+                   .format(data_element.tag))
+            raise ValueError(msg)
     else:
         # write the proper length of the data_element in the length slot,
         # unless is SQ with undefined length.

Handling of DS too long to be encoded in explicit encoding
<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->

#### Description
This is probably not a bug, but I'm not sure about the wanted behavior.
An RTPlan dataset encoded as Little Endian Implicit contains multiple values in the DS tag DHV Data (3004,0058) with an overall length not fitting into 2 bytes. Trying to write this as explicit Little Endian fails with an exception (`"ushort format requires 0 &lt;= number &lt;= (0x7fff * 2 + 1)"`) which is raised by the `pack` call in `write_leUS` while trying to write the length.

The standard says for this case in PS3.5, Table 6.2-1 (for VR DS):
```
Note
Data Elements with multiple values using this VR may not be properly encoded if Explicit-VR transfer syntax is used and the VL of this attribute exceeds 65534 bytes.
```
So, as I understand it, this is valid DICOM, that cannot be converted to explicit encoding without data loss.
The question is how to handle this. What comes to mind:
- truncate the value and log a warning
- raise a meaningful exception
- adapt the behavior depending on some config setting

Any thoughts?

<!-- Example: Attribute Error thrown when printing (0x0010, 0x0020) patient Id> 0-->

#### Steps/Code to Reproduce
<!--
Example:
```py
from io import BytesIO
from pydicom import dcmread

bytestream = b'\x02\x00\x02\x00\x55\x49\x16\x00\x31\x2e\x32\x2e\x38\x34\x30\x2e\x31' \
             b'\x30\x30\x30\x38\x2e\x35\x2e\x31\x2e\x31\x2e\x39\x00\x02\x00\x10\x00' \
             b'\x55\x49\x12\x00\x31\x2e\x32\x2e\x38\x34\x30\x2e\x31\x30\x30\x30\x38' \
             b'\x2e\x31\x2e\x32\x00\x20\x20\x10\x00\x02\x00\x00\x00\x01\x00\x20\x20' \
             b'\x20\x00\x06\x00\x00\x00\x4e\x4f\x52\x4d\x41\x4c'

fp = BytesIO(bytestream)
ds = dcmread(fp, force=True)

print(ds.PatientID)
```
If the code is too long, feel free to put it in a public gist and link
it in the issue: https://gist.github.com

When possible use pydicom testing examples to reproduce the errors. Otherwise, provide
an anonymous version of the data in order to replicate the errors.
-->

#### Expected Results
<!-- Please paste or describe the expected results.
Example: No error is thrown and the name of the patient is printed.-->

#### Actual Results
<!-- Please paste or specifically describe the actual output or traceback.
(Use %xmode to deactivate ipython's trace beautifier)
Example: ```AttributeError: 'FileDataset' object has no attribute 'PatientID'```
-->

#### Versions
<!--
Please run the following snippet and paste the output below.
import platform; print(platform.platform())
import sys; print("Python", sys.version)
import pydicom; print("pydicom", pydicom.__version__)
-->


<!-- Thanks for contributing! -->

diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py
index a3e0ed988..2eaa4d428 100644
--- a/pydicom/tests/test_filewriter.py
+++ b/pydicom/tests/test_filewriter.py
@@ -2419,3 +2419,34 @@ class TestWriteUndefinedLengthPixelData(object):
             ds_unzipped = dcmread(fp)
             for elem_in, elem_out in zip(ds, ds_unzipped):
                 assert elem_in == elem_out
+
+    def test_writing_too_big_data_in_explicit_encoding(self):
+        """Data too large to be written in explicit transfer syntax."""
+        self.fp.is_little_endian = True
+        self.fp.is_implicit_VR = True
+        # make a multi-value larger than 64kB
+        single_value = b'123456.789012345'
+        large_value = b'\\'.join([single_value] * 4500)
+        # can be written with implicit transfer syntax,
+        # where the length field is 4 bytes long
+        pixel_data = DataElement(0x30040058, 'DS',
+                                 large_value,
+                                 is_undefined_length=False)
+        write_data_element(self.fp, pixel_data)
+
+        self.fp = DicomBytesIO()
+        self.fp.is_little_endian = True
+        self.fp.is_implicit_VR = False
+        # shall raise if trying to write it with explicit transfer syntax,
+        # where the length field is 2 bytes long
+        expected_message = (r'The value for the data element \(3004, 0058\) '
+                            r'exceeds the size of 64 kByte ')
+        with pytest.raises(ValueError, match=expected_message):
+            write_data_element(self.fp, pixel_data)
+
+        self.fp = DicomBytesIO()
+        self.fp.is_little_endian = False
+        self.fp.is_implicit_VR = False
+        # we expect the same behavior in Big Endian transfer syntax
+        with pytest.raises(ValueError, match=expected_message):
+            write_data_element(self.fp, pixel_data)

pip install -e .[dev]
parse_log_pytest
requirements.txt
pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio
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==22.2.0
certifi==2021.5.30
coverage==6.2
execnet==1.9.0
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
-e git+https://github.com/pydicom/pydicom.git@639efac4450392ef1d89159055fdc5af474ed174#egg=pydicom
pyparsing==3.1.4
pytest==7.0.1
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0

name: pydicom
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
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_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
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - pip=21.2.2=py36h06a4308_0
  - 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
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - attrs==22.2.0
      - coverage==6.2
      - execnet==1.9.0
      - importlib-metadata==4.8.3
      - iniconfig==1.1.1
      - packaging==21.3
      - pluggy==1.0.0
      - py==1.11.0
      - pyparsing==3.1.4
      - pytest==7.0.1
      - pytest-asyncio==0.16.0
      - pytest-cov==4.0.0
      - pytest-mock==3.6.1
      - pytest-xdist==3.0.2
      - tomli==1.2.3
      - typing-extensions==4.1.1
      - zipp==3.6.0
prefix: /opt/conda/envs/pydicom

pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding
pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose pydicom/tests/test_filewriter.py::TestWriteFile::testCT pydicom/tests/test_filewriter.py::TestWriteFile::testMR pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000 pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000 pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip
doc/whatsnew/v1.3.0.rst pydicom/filewriter.py
doc/whatsnew/v1.3.0.rst pydicom/filewriter.py