java - 用户定义的 CORBA 异常在编译后给我错误

标签 java c++ exception corba

我在使用 CORBA 中自己的用户定义异常时遇到了一些麻烦。这是我非常简单的代码:

interface Interfface
{
    exception myOwnException {};

    void ffunction(in double arg) raises (myOwnException);
};

#include "Interfface.hh"

class Implementation : public POA_Interfface
{
    public :
        virtual void ffunction(double arg) throw (myOwnException);
};

#include "Implementation.h"

void Implementation::ffunction(double arg) throw (myOwnException)
{   
    arg ++;    
    throw (myOwnException);
}

当我编译 Implementation.cpp 时,它给了我一些错误(http://pastie.org/private/a22ikk09zkm9tqywn37w):

Implementation.cpp: In member function ‘virtual void Implementation::ffunction(double)’:
Implementation.cpp:5: error: ‘myOwnException’ was not declared in this scope
In file included from Implementation.cpp:1:
Implementation.h:6: error: expected type-specifier before ‘myOwnException’
Implementation.h:6: error: expected ‘)’ before ‘myOwnException’
Implementation.h:6: error: expected ‘;’ before ‘myOwnException’
Implementation.cpp:3: error: expected type-specifier before ‘myOwnException’
Implementation.cpp:3: error: expected ‘)’ before ‘myOwnException’
Implementation.cpp:3: error: expected initializer before ‘myOwnException’

这段代码有什么问题?还有一个问题:我怎样才能用 Java 做同样的事情?

这是我的代码:http://speedy.sh/F5utX/user-defined-exception.tar我在 java 中做了同样的事情(代码也在 user-defined-exception.tar 中)但是 java 代码给了我这个:

Note: InterffacePOA.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

最佳答案

您应该创建异常类型的新实例,如下所示:

throw myOwnException();

您可能还需要限定命名空间:

throw Interfface::myOwnException();

顺便说一下,throw 声明在大多数(读作“所有”)编译器实现中实际上没有任何有用的效果,并且在 C++11 中被弃用。我知道它们可能是在这里自动生成的,但仍然很高兴知道。我发现在实践中,这些声明往往会随着源代码的后续更改而变得不准确。不要将它们拖到您的实现文件中。 另一方面,您使用了无意义的变量和类型名称,并且没有一致的命名约定。

编辑: 正如 Johnny Willemsen 所说,您可以像这样向异常(exception)添加成员:

exception myOwnException {
    string reason;
};

每个异常成员都将表示为公共(public)类成员。将生成必要的构造函数,因此您可以像这样抛出这样的异常:

throw Interfface::myOwnException("Wrong polarity!");

当抛出异常时,如果它没有在本地被捕获,那么它会被序列化并传播到客户端(远程过程调用者)。在那里它将被反序列化,因此您可以像这样捕获它并访问它的成员:

try
{
    server->ffunction(0);
}
catch(const Interfface::myOwnException &ex)
{
    std::cout << ex.reason;
}

在 C++ 中,您通常通过常量引用捕获异常(这也取决于它是如何抛出的)。 我是凭内存写的(CORBA 的东西),所以我希望我没有遗漏任何重要的东西。

关于java - 用户定义的 CORBA 异常在编译后给我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10459993/

相关文章:

java - Android GridLayout 边框

c++ - 有没有办法减少 ostringstream malloc/free 的?

c# - NLog LoggerFactory 中的 TypeInitializationException

从 request.getInputStream() 读取字符时出现 java.io.IOException : Stream closed or Underlying input stream returned zero bytes,

java - S3 SDK 在上传时更新单个对象而不是创建新文件

java - 递归 id 生成返回错误值,但生成正确值?

c++ - G++ 在 makefile 中使用时停止工作

c++ - 从 C++ Gui 获取输入到另一个 C++ 程序

c# - .NET 4 exe 崩溃并显示 80131506 退出代码

Java:通过Spring创建基于OCP的工厂?