Commit fba1b7c5 authored by Giovanni La Mura's avatar Giovanni La Mura
Browse files

Introduce class-oriented list exception management

parent fc4b82fe
Loading
Loading
Loading
Loading
+45 −6
Original line number Diff line number Diff line
/*! \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