C++ 异常

C++异常通过保留字 trythrowcatch 进行管理。

请参阅编译器的文档或参考书目中的某个 C++ 书籍以获取更多信息。

以下是样本 ICC$EXC1 (请参阅 C++ 样本程序):
#include "icceh.hpp"
#include "iccmain.hpp"
class Test {
public:
void tryNumber( short num ) {
IccTerminal* term = IccTerminal::instance();
*term << "Number passed = " << num << endl <<
flush;
if ( num > 10 ) {
*term << ">>Out of Range - throwing exception" << endl
<< flush;
throw "!!Number is out of range!!";
}
}
};

前两行包括 Foundation Classes 的头文件以及用于为应用程序设置操作环境的标准 main 函数。

然后,我们声明类 Test ,它有一个公用方法 tryNumber 。 此方法以内联方式实现,以便在传递大于 10 的整数时抛出异常。 我们还会向 CICS® 终端写出一些信息。
void IccUserControl::run()
{
IccTerminal* term = IccTerminal::instance();
term->erase();
*term << "This is program 'icc$exc1' ..." << endl;
try {
Test test;
test.tryNumber( 1 );
test.tryNumber( 7 );
test.tryNumber( 11 );
test.tryNumber( 6 );
}
catch( const char* exception ) {
term->setLine( 22 );
*term << "Exception caught: " << exception << endl
<< flush;
}
term->send( 24,1,"Program 'icc$exc1' complete: Hit PF12 to End" );
term->waitForAID( IccTerminal::PF12 );
term->erase();
return;
}

IccUserControl 运行方法包含本例的用户代码。

擦除终端显示并写入一些文本后,我们开始 try 块。 try 块可以限定任意数量的 C++ 代码行。

在此,我们创建一个 Test 对象,并使用各种参数调用唯一的方法 tryNumber 。 前两次调用 (1 或 7) 成功,但第三次调用 (11) 导致 tryNumber 抛出异常。 未执行第四次 tryNumber 调用 (6) ,因为异常导致程序执行流离开当前 try 块。

然后,保留 try 块并查找合适的 catch 块。 合适的 catch 块是具有与要抛出的异常类型兼容的自变量的块 (此处为 char * )。 catch 块将消息写入 CICS 终端,然后在 catch 块之后的行处恢复执行。

此 CICS 程序的输出如下所示:
This is program 'icc$exc1' ...
					Number passed = 1
					Number passed = 7
					Number passed = 11
					>>Out of Range - throwing exception
					Exception caught: !!Number is out of range!!
					Program 'icc$exc1' complete: Hit PF12 to End

CICS C++ 基础类不会像先前样本中一样抛出 char * 异常,而是改为抛出 IccException 对象。

有几种类型的 IccExceptiontype 方法返回指示类型的枚举。 以下是对每种类型的依次描述。
objectCreationError
尝试创建对象无效。 例如,如果尝试创建单独类的第二个实例 (例如 IccTask) ,那么会发生此情况。
invalidArgument
使用无效参数调用了方法。 例如,如果应用程序将数据量过大的 IccBuf传递给 IccTempStore writeItem ,就会出现这种情况。

当尝试创建 IccResourceId 的子类(如 IccTermId 时,如果字符串过长,也会出现这种情况。

可以在 C++ 样本程序 中找到以下样本,作为文件 ICC$EXC2 。 此处提供了样本,没有许多终端 IO 请求。
#include "icceh.hpp"
#include "iccmain.hpp"
void IccUserControl::run()
{
try
{
IccTermId id1( "1234" );
IccTermId id2( "12345");
}
catch( IccException& exception )
{
terminal()->send( 21, 1, exception.summary() );
}
return;
}

在前面的示例中,第一个 IccTermId成功创建,但第二个对象导致抛出 IccException ,因为字符串“12345”有5个字节,而只允许4个字节。 请参阅 C++ 样本程序 ,以获取此样本程序的预期输出。

invalidMethodCall
无法调用方法。 典型原因是对象无法在其当前状态下执行调用。 例如,只有在指定 要读取的记录 IccRecordIndex与文件关联时, IccFile readRecord才会生效。
CICSCondition
IccCondition 结构中列出的 CICS 条件已在对象中发生,并且对象已配置为抛出异常。
familyConformanceError
已开启此程序的系列子集实施,并且已尝试在所有受支持的平台上执行无效的操作。
internalError
CICS 基础类检测到内部错误。 请致电服务。