Untitled

 avatar
unknown
plain_text
a year ago
1.1 kB
28
Indexable
CustomException.h


#ifndef CUSTOMEXCEPTION_H
#define CUSTOMEXCEPTION_H

#include <stdexcept>
#include <string>

class OutOfRangeException : public std::out_of_range {
public:
    OutOfRangeException(const std::string& message) : std::out_of_range(message) {}
};

#endif










CustomException.cpp


#include "CustomException.h"





ArrayAccess.cpp


#include "CustomException.h"

int getFromArray(int index) {
    int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    if (index < 0 || index >= 10) {
        throw OutOfRangeException("Index out of range: " + std::to_string(index));
    }
    
    return array[index];
}










main.cpp



#include <iostream>
#include "CustomException.h"

int getFromArray(int index);

int main() {
    try {
        int val = getFromArray(5);
        std::cout << "Value at index 5: " << val << std::endl;
        
        val = getFromArray(-1); // This will throw an exception
        val = getFromArray(20); // This will also throw an exception
    } catch (const OutOfRangeException& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }
    
    return 0;
}
Editor is loading...
Leave a Comment