diff --git a/connection.cpp b/connection.cpp
index b7623e6..3e4e3dc 100644
--- a/connection.cpp
+++ b/connection.cpp
@@ -313,13 +313,15 @@ int DBconn::ExecuteVoid(const wxString &query)
 
 wxString DBconn::GetLastError()
 {
+	size_t len = lastError.length();
+
 	// Return the last error message, minus any trailing line ends
-	if (lastError.substr(lastError.length() - 2, 2) == wxT("\r\n")) // DOS
-		return lastError.substr(0, lastError.length() - 2);
-	else if (lastError.substr(lastError.length() - 1, 1) == wxT("\n")) // Unix
-		return lastError.substr(0, lastError.length() - 1);
-	else if (lastError.substr(lastError.length() - 1, 1) == wxT("\r")) // Mac
-		return lastError.substr(0, lastError.length() - 1);
+	if (len >= 2 && lastError.substr(len - 2, 2) == wxT("\r\n")) // DOS
+		return lastError.substr(0, len - 2);
+	else if (len >= 1 && lastError.substr(len - 1, 1) == wxT("\n")) // Unix
+		return lastError.substr(0, len - 1);
+	else if (len >= 1 && lastError.substr(len - 1, 1) == wxT("\r")) // Mac
+		return lastError.substr(0, len - 1);
 	else
 		return lastError;
 }
