From fba1b7c559638162eb94dced5ebd07c1212d33a6 Mon Sep 17 00:00:00 2001
From: Giovanni La Mura <giovanni.lamura@inaf.it>
Date: Thu, 19 Oct 2023 10:54:12 +0200
Subject: [PATCH] Introduce class-oriented list exception management

---
 src/include/List.h | 51 ++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 45 insertions(+), 6 deletions(-)

diff --git a/src/include/List.h b/src/include/List.h
index 047616aa..0e13f0f9 100644
--- a/src/include/List.h
+++ b/src/include/List.h
@@ -1,9 +1,46 @@
 /*! \file List.h
  */
 
-#ifndef LIST_OUT_OF_BOUNDS_EXCEPTION
-#define LIST_OUT_OF_BOUNDS_EXCEPTION 1
-#endif
+#ifndef INCLUDE_LIST_H_
+#define INCLUDE_LIST_H_
+
+#include <exception>
+#include <string>
+
+/**
+ * \brief Exception for out of bounds list requests.
+ */
+class ListOutOfBoundsException: public std::exception {
+protected:
+	int min_index, max_index, requested_index;
+
+public:
+	/**
+	 * \brief Exception instance constructor.
+	 *
+	 * \param requested: `int` The index that was requested.
+	 * \param min: `int` The minimum index allowed by the list.
+	 * \param max: `int` The maximum index allowed by the list.
+	 */
+	ListOutOfBoundsException(int requested, int min, int max) {
+		min_index = min;
+		max_index = max;
+		requested_index = requested;
+	}
+	/**
+	 * \brief Exception message.
+	 */
+	virtual const char* what() const throw() {
+		std::string message = "Error: requested index ";
+		message += requested_index;
+		message += " is out of range [";
+		message += min_index;
+		message += ", ";
+		message += (max_index - 1);
+		message += "]";
+		return message.c_str();
+	}
+};
 
 /**
  * \brief A class to represent dynamic lists.
@@ -52,7 +89,7 @@ template<class T> class List {
     size = length;
     first = new element;
     first->p_prev = NULL;
-    element *current = first;
+    current = first;
     element *p_prev = first;
     for (int i = 1; i < size; i++) {
       current = new element;
@@ -103,7 +140,7 @@ template<class T> class List {
    */
   T get(int index) {
     if (index < 0 || index > size - 1) {
-      throw LIST_OUT_OF_BOUNDS_EXCEPTION;
+      throw ListOutOfBoundsException(index, 0, size - 1);
     }
     current = last;
     for (int i = size - 1; i > index; i--) current = current->p_prev;
@@ -131,7 +168,7 @@ template<class T> class List {
    */
   void set(int index, T value) {
     if (index < 0 || index > size - 1) {
-      throw LIST_OUT_OF_BOUNDS_EXCEPTION;
+        throw ListOutOfBoundsException(index, 0, size - 1);
     }
     current = last;
     for (int i = size - 1; i > index; i--) current = current->p_prev;
@@ -161,3 +198,5 @@ template<class T> class List {
     return array;
   }
 };
+
+#endif
-- 
GitLab