diff --git a/src/pl/plpython/plpy_elog.c b/src/pl/plpython/plpy_elog.c
index 7c627eacfbf..aa1cf17b366 100644
--- a/src/pl/plpython/plpy_elog.c
+++ b/src/pl/plpython/plpy_elog.c
@@ -359,7 +359,10 @@ PLy_get_sqlerrcode(PyObject *exc, int *sqlerrcode)
 
 	sqlstate = PyObject_GetAttrString(exc, "sqlstate");
 	if (sqlstate == NULL)
+	{
+		PyErr_Clear();
 		return;
+	}
 
 	buffer = PLyUnicode_AsString(sqlstate);
 	if (strlen(buffer) == 5 &&
@@ -395,6 +398,7 @@ PLy_get_spi_error_data(PyObject *exc, int *sqlerrcode, char **detail,
 	}
 	else
 	{
+		PyErr_Clear();
 		/*
 		 * If there's no spidata, at least set the sqlerrcode. This can happen
 		 * if someone explicitly raises a SPI exception from Python code.
@@ -571,6 +575,10 @@ get_string_attr(PyObject *obj, char *attrname, char **str)
 	{
 		*str = pstrdup(PLyUnicode_AsString(val));
 	}
+	else if (val == NULL)
+	{
+		PyErr_Clear();
+	}
 	Py_XDECREF(val);
 }
 
