【问题标题】:Constructor c++ and handling exception构造函数 c++ 和处理异常
【发布时间】:2016-01-08 16:24:15
【问题描述】:

我得到了 Maze 类来生成随机迷宫。所以我面临的问题是我想抛出一些关于迷宫大小的异常(我想放一个最小值),如果列数是对的(我需要使迷宫对称)。所以我不知道如何处理三个或四个不同的异常并生成错误消息

class Maze { 
  private: 

    int nr; // number of rows
    int nc; // number of columns
    int complex; // complexity of the maze: how hard to leave
    vector< vector<int> > vec; //array bidimensional de enteros
    //vector de dos dimensiones
    /*vector<T> elems;     // elements 
     // Create
    vector< vector<int> > vec(4, vector<int>(4));
    // Write
    vec[2][3] = 10;
    // Read
    int a = vec[2][3];*/
  public: 

    void Maze();
    void Maze( int rows, int columns, int hard);
    void PrintMaze();
    void ShowMaze(vec);
    bool isConnected ();
    void explore (Node posicion);
    bool validMove( Node actual);
    Node RandomNode(); // Obtienes un nodo al azar valido
    Node MirrorNode (Node actual); //devuelve el nodo espejo/mirror de un nodo null en otro caso..
    void reverseExplore();
    int getnr();
    int getnc();
    int getComplex();
    void setnr();
    void setnc();
    void setComplex();
    } 
}; 
void Maze::Maze(void) {
         cout <<"No hace naA"<<"\n\n";
}


void Maze::Maze(int rows, int columns, int hard) {

        //Comprobar numer filas y columnas es par/impar y sino salir dando mensaje correspondiente
    /*
    if (nr %2) != 0) {
        fprintf(stderr, "Error: El numero de filas tiene que ser par/impar.\n");
        exit();
        return 101;
    } else if (nc % 2 != 0) {
        fprintf(stderr, "Error: El numero de filas tiene que ser par/impar", nproc);
        return 102;
    }

    if (mr < 20 || nc < 10) {
        fprintf(stderr, "Error: El laberinto tiene que tener al menosu unas medidas\n");
        exit();
        return 103;
    }
*/
    nr=rows;
    nc=columns;
    hard=0;
    bool Final=false;
    Node actualNode;
    setupMaze();   //Inicializar laberinto ( todo a 0, poner los  bordes y casilla inicial)

    do {
        actualNode=randomNode();     //Obtengo un nodo aleatorio valido: que no sea pared y este en los limites
        addNode(actualNode); //Añado el nodo al laberinto
        if ( isConnected();) {
            //hard=0; //opcional para contar solo las veces que intenta en el  "mismo intento", ahora al colocar el nodo bien puedes inicializar los intentos a 0.
            cout << "\nInsercion correcta del nodo\n"; // compruebo si el laberinto es conexo o nodo
        }
        else {
            //Si laberinto resultante no es conexo, tengo que deshacer la inserción del nodoactual e incrementar el valor de hard
            deletenode( actualNode);
            hard++; 
        }
    while ( hard <= complex)

}

我需要在 C++ 中用 C 制作类似的东西。我会用 mymaze.maze(40,80,10) 生成一个迷宫。我需要控制这些值以生成对称迷宫并确保输入变量具有有效值(行数必须成对,迷宫的最小尺寸必须为 20x10):

if (nr %2) != 0) {
            fprintf(stderr, "Error: El numero de filas tiene que ser par/impar.\n");
            exit();
            return 101;
        } else if (nc % 2 != 0) {
            fprintf(stderr, "Error: El numero de filas tiene que ser par/impar", nproc);
            return 102;
        }

        if (mr < 20 || nc < 10) {
            fprintf(stderr, "Error: El laberinto tiene que tener al menosu unas medidas\n");
            exit();
            return 103;
        }
    */

提前致谢

【问题讨论】:

  • 查看这个堆栈溢出页面,应该很有用:link to similar question
  • 每当您在 C 中编写错误消息时,请改为抛出异常。当您尝试这样做时会发生什么?
  • 谢谢,但我不知道该怎么做.. 任何人都可以举一些简单的例子来说明如何在 c++ 中尝试捕获一些例子(ej: nc 是对数)......你是什么指出只抛出异常并且不知道他们在哪里捕获它..

标签: c++ constructor exception-handling maze


【解决方案1】:

你可以用throwexception 代替fprintf() + exit()

抛出异常

这是一个抛出异常的例子(参见Maze::Maze() 实现):

#include <iostream>
#include <stdexcept>

class Maze { 
public: 
    Maze();
    Maze(int rows, int columns, int hard);
private:
    int nr;
    int nc;
};

Maze::Maze(void) {
    std::cout << "No hace naA\n\n";
}

Maze::Maze(int rows, int columns, int hard) {

    if (rows % 2 != 0 || columns % 2 != 0)
        throw std::invalid_argument("Error: El numero de filas tiene que ser par/impar");

    if (rows < 20 || columns < 10) 
        throw std::out_of_range("Error: El laberinto tiene que tener al menosu unas medidas");

    // setup the maze ...
}

int main() {
    Maze m(41,80,10);  // 'invalid_argument' exception
    Maze m(2,2,10);    // 'out_of_range' exception
}

这个程序抛出一个invalid_argument 异常,因为rows 不是偶数。 输出是:

terminate called after throwing an instance of 'std::invalid_argument'
  what():  Error: El numero de filas tiene que ser par/impar

捕捉异常

以下是捕获异常的示例:

int main() {
    try {
        Maze m(41,80,10);
    } catch (const std::invalid_argument& e) {            
        std::cout << e.what() << std::endl;
        std::cout << "maze is not symetric" << std::endl;
    } catch (const  std::out_of_range& e) {
        std::cout << e.what() << std::endl;
        std::cout << "maze is too small" << std::endl;
    } catch (...) {
        std::cout << "some other exception" << std::endl;
    }
}

另一种方法(没有例外)

您可以“修复”不正确的用户输入,而不是抛出异常:

Maze::Maze(int rows, int columns, int hard) {

    if (rows % 2 != 0)
        rows += 1;

    if (columns % 2 != 0)
        columns += 1;

    if (rows < 20)
        rows = 20;        

    if (columns < 10) 
        columns = 10;

    // setup the maze ...
 }

【讨论】:

  • 非常感谢您的帮助。我有足够的抛出异常而不捕获吗?我不喜欢在 main 函数中捕获异常的解决方案,因为 main 只能由客户或类用户(而不是程序员或开发人员)使用。是否有任何选项可以在类的构造函数中捕获异常?另外,我在哪里可以获得更多 std 错误作为无效参数和超出范围?
  • @EduardoGutierrez“抛出异常而不捕获”是可以的,如果用户输入错误,程序将结束。
  • @EduardoGutierrez 在构造函数中捕获异常没有意义。您可以修复不正确的输入,请参阅更新。
  • 好的,我认为这是一个更礼貌的解决方案。我将向用户抛出带有消息错误的异常,例如:“错误:列数必须成对”,因此程序将停止并具有受控终止。用户将获得有关错误的信息。认为它的更好的解决方案。你不这么认为吗?非常感谢您的帮助。
  • @EduardoGutierrez 是的,我认为在这种情况下抛出异常是一个很好的解决方案。
猜你喜欢
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 2021-04-08
相关资源
最近更新 更多