如何正确处理头文件中的异常

How to correctly handle exceptions in a header?

本文关键字:异常 文件 正确处理      更新时间:2023-10-16

我正在处理一个包含多个项目的程序的异常。我决定在一个致力于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;
}
(演示)