gpt4 book ai didi

c++ - try catch 模板类中定义的异常

转载 作者:行者123 更新时间:2023-11-28 08:13:34 24 4
gpt4 key购买 nike

我正在尝试使用链表实现优先级队列,但我遇到了 try/catch 问题。以下是优先级队列头文件的相关部分:

#ifndef PRIORITYQUEUELINKED_H
#define PRIORITYQUEUELINKED_H

#include "RuntimeException.h"
#include <list>

using namespace std;

template <typename E, typename C> // uses data type and some total order relation
class PriorityQueueLinked {

// code for PriorityQueueLinked

class EmptyPriorityQueueException : public RuntimeException {
public:
EmptyPriorityQueueException() :
RuntimeException("Empty priority queue") {}
};

// more code

#endif

这是 RuntimeException 头文件:

#ifndef RUNTIMEEXCEPTION_H_
#define RUNTIMEEXCEPTION_H_

#include <string>

class RuntimeException {// generic run-time exception
private:
std::string errorMsg;
public:
RuntimeException(const std::string& err) { errorMsg = err; }
std::string getMessage() const { return errorMsg; }
};

inline std::ostream& operator<<(std::ostream& out, const RuntimeException& e)
{
out << e.getMessage();
return out;
}

#endif

这是我的主要内容:

#include "PriorityQueueLinked.h"
#include "Comparator.h"
#include <iostream>

using namespace std;

int main() {
try {
PriorityQueueLinked<int,isLess> prique; // empty priority queue
prique.removeMin(); // throw EmptyPriorityQueueException
}
catch(...) {
cout << "error" << endl << endl;
}
getchar();
return 0;
}

我的问题在于无法为 catch 配置“...”的替换项。我尝试了几种方法,其中之一是:“catch(PriorityQueueLinked < int,isLess >::EmptyPriorityQueueException E)”,但在这种情况下,它表示 EmptyPriorityQueueException 不是 PriorityQueueLinked 的成员。任何建议将不胜感激。谢谢

最佳答案

Try-catch 支持异常类的继承。 catch (const RuntimeException & ex)将捕获 RuntimeException 的任何子类,即使它是私有(private)的。这就是派生异常类的全部要点。

对了,永远不要写using namespace std;是标题,您永远无法知道谁包含它以及如何包含它。标准库也已经有了你的通用异常类,真是令人惊讶!他们还称它为运行时异常,异常是这样写的:std::runtime_exception .您可以在 <stdexcept> 中找到它.

关于c++ - try catch 模板类中定义的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8371151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com