如何正确处理头文件中的异常
How to correctly handle exceptions in a header?
我正在处理一个包含多个项目的程序的异常。我决定在一个致力于ExceptionHandling的项目中有一个标题"ExceptionHandling"。因此,我提出了以下代码:/*该对象管理所有可能的异常:standards/automatic and specific */
#ifndef EXCEPTIONHANDLING_H
#define EXCEPTIONHANDLING_H
//#include "Stdafx.h"
#include <iostream>
#include <exception> // Standard exceptions
using namespace std;
// Longitude Exception
class LonEx: public exception
{
virtual const char* what() const throw()
{
return "**** ERROR: Longitude cannot be higher than 180 degreesnn";
}
} exceptionLongitude;
// Negative Exception
class NegativeEx: public exception
{
virtual const char* what() const throw()
{
return "**** ERROR: Negative value is not possible in ";
}
} exceptionNegative;
// Xml exception (file cannot be opened)
class XmlEx: public exception
{
virtual const char* what() const throw()
{
return "**** ERROR: XML parsed with errors. Unable to open file called ";
}
} exceptionXml;
#endif
然后,在捕获异常的文件中,我将继续这样做:"throw exceptionLatitude;"。
问题是,当我在两个cpp文件中使用它时,这会给我错误LNK2005(已经定义)。我试图把定义在一个cpp文件,但我没有成功。有人能帮我吗?我也想知道,如果它是好的有这么多的类在一个头。
您尝试对异常使用全局变量。尽量简化和使用局部对象:不声明类和变量,只声明类,例如
class LonEx: public exception
{
virtual const char* what() const throw()
{
return "**** ERROR: Longitude cannot be higher than 180 degreesnn";
}
};
不含exceptionLongitude
。当你想抛出
throw LonEx();
是exceptionLongitude, exceptionNegative, exceptionXml把你搞砸了。你不需要他们。
不做throw exceptionXml;
不如这样做:
throw XmlEx();
只要从你的。h中删除那些定义(exceptionLongitude, exceptionNegative, exceptionXml),你就不需要一个。cpp了。
简而言之,声明属于。h,定义属于。cpp。但是为了使用类类型的声明,您不需要定义异常类的实例。
如果您所做的只是在这些情况下更改what
消息,我将使用具有适当构造函数的内置异常。
错误:经度不能高于180度nn
错误:
中不可能有负值
明显是invalid_argument
ERROR: XML被错误解析。无法打开名为
的文件
并且可能是system_error
(未找到文件,拒绝许可)。
例如
int mydiv(int x, int y){
if (y == 0){
throw std::invalid_argument("**** ERROR: Zero value is not possible as denominator.");
}
return x/y;
}
(演示)相关文章:
- 加载与引用 .NET DLL 位于同一文件夹中的引用的 .NET DLL 时"Not found"异常
- 读取文件时引发异常
- 尝试将数字写入二进制文件时引发异常
- 为什么我尝试在 OpenGL 中加载的 3ds 文件会出现此未经处理的异常?
- 如何构建一个异常类来报告C++中的哪些文件和行号?
- 从二进制文件中读取元素时引发异常(引发异常:读取访问冲突. _Pnext 0xB414D4)
- 读取 MAC 地址时文件读取异常
- free():在有效指针异常中-使用流读取巨大文件时
- 尝试将 std::cerr 重定向到文件时出现访问冲突异常
- 文件流析构函数是否可以在C++中引发异常?
- 挂钩创建文件抛出异常:读取访问冲突
- 仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够
- 如果文件为c ,如何抛出异常
- 尝试使用 wxWidgets 从 zip 打开不存在的文件时无法捕获的异常
- 加载C DLL文件时,如何修复异常_access_violation
- C++ 读取文件和写入变量时未处理的异常 - getline 错误?
- G++ 和 CL(VS2017) 都编译成功,但 cl 编译的可执行文件运行异常
- 食人魔异常(6:文件未找到异常):找不到'ogre.cfg'文件
- 系统访问出界异常,尝试从flatbuffer的二进制文件访问"LengthofTable"
- 提升序列化在从二进制文件读取时引发异常