C++ 中的异常处理
From Apache OpenOffice Wiki
< Zh | Documentation
要抛出和捕获 UNO 异常,可使用常规的 C++ 异常处理机制。调用 UNO 接口可能仅抛出 com::sun::star::uno::Exception 或派生的异常。以下示例可捕获每个可能的异常:
try
{
Reference< XInterface > rInitialObject =
xUnoUrlResolver->resolve( OUString::createFromAsci(
"uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" ) );
}
catch( com::sun::star::uno::Exception &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "An error occurred: %s\n", o.pData->buffer );
}
如果希望对每个可能的异常类型做出不同的反应,请查找可能由某个特定方法抛出的异常。例如,com.sun.star.bridge.XUnoUrlResolver 中的 resolve() 方法可以抛出三种异常。分别捕获每种异常类型:
try
{
Reference< XInterface > rInitialObject =
xUnoUrlResolver->resolve( OUString::createFromAsci(
"uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" ) );
}
catch( ConnectionSetupException &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "couldn't access local resource ( possible security resons )\n" );
}
catch( NoConnectException &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "no server listening on the resource\n" );
}
catch( IllegalArgumentException &e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "uno URL invalid\n" );
}
catch( RuntimeException & e )
{
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
printf( "%s\n", o.pData->buffer );
printf( "an unknown error has occurred\n" );
}
实现您自己的 UNO 对象时(请参阅 编写 UNO 组件 - C++ 组件),使用常规的 C++ throw 语句抛出异常:
void MyUnoObject::initialize( const Sequence< Any > & args.getLength() ) throw( Exception )
{
// we expect 2 elements in this sequence
if( 2 != args.getLength() )
{
// create an error message
OUStringBuffer buf;
buf.appendAscii( "MyUnoObject::initialize, expected 2 args, got " );
buf.append( args.getLength() );
buf.append( "." );
// throw the exception
throw Exception( buf.makeStringAndClear() , *this );
}
...
}
请注意:UNO 接口方法只能抛出从 com::sun::star::uno::Exception 派生的异常。如果调用程序和被调用的对象不是位于同一 UNO 运行时环境,就不能通过 UNO 运行时桥接其他异常(例如,C++ std::exception)。而且,多数当前 Unix C++ 编译器(例如,gcc 3.0.x)不编译代码。编译期间,派生类中的异常规范被放宽,可以抛出除派生的接口中指定的异常以外的异常。抛出未指定的异常会导致 std::unexpected 异常,并且 Unix 系统会中止程序。
| Content on this page is licensed under the Public Documentation License (PDL). |