diff --git a/python/paddle/fluid/dygraph/dygraph_to_static/error.py b/python/paddle/fluid/dygraph/dygraph_to_static/error.py index 3b868ade4e29b82ec06a4b51e290a326ba9a5117..93670758dae77e864a93318924162724c53fd9a8 100644 --- a/python/paddle/fluid/dygraph/dygraph_to_static/error.py +++ b/python/paddle/fluid/dygraph/dygraph_to_static/error.py @@ -143,6 +143,10 @@ class SuggestionDict(object): return self.suggestion_dict[key] +class Dy2StKeyError(Exception): + pass + + class ErrorData(object): """ Error data attached to an exception which is raised in un-transformed code. @@ -159,7 +163,10 @@ class ErrorData(object): def create_exception(self): message = self.create_message() - new_exception = self.error_type(message) + if self.error_type is KeyError: + new_exception = Dy2StKeyError(message) + else: + new_exception = self.error_type(message) setattr(new_exception, ERROR_DATA, self) return new_exception diff --git a/python/paddle/fluid/tests/unittests/dygraph_to_static/test_error.py b/python/paddle/fluid/tests/unittests/dygraph_to_static/test_error.py index 7d980b5f75a62f0b4a3dc19836d313ebc52d3ecd..27d7389b903cc481844783e4c861b83b56febf7d 100644 --- a/python/paddle/fluid/tests/unittests/dygraph_to_static/test_error.py +++ b/python/paddle/fluid/tests/unittests/dygraph_to_static/test_error.py @@ -443,6 +443,20 @@ class TestSuggestionErrorInRuntime(TestErrorBase): for disable_new_error in [0, 1]: self._test_raise_new_exception(disable_new_error) +@paddle.jit.to_static +def func_ker_error(x): + d = { + 'x': x + } + y = d['y'] + x + return y + +class TestKeyError(unittest.TestCase): + def test_key_error(self): + paddle.disable_static() + with self.assertRaises(error.Dy2StKeyError): + x = paddle.to_tensor([1]) + func_ker_error(x) if __name__ == '__main__': unittest.main()