except40.c

来自「开放源码的编译器open watcom 1.6.0版的源代码」· C语言 代码 · 共 64 行

C
64
字号
#include "fail.h"

struct Except {
};
struct ExceptA : Except {
};
struct ExceptB : Except {
};
struct ExceptC : Except {
};
	

void do_throw( int which ) {
    switch( which ) {
    case 'a':
	throw ExceptA();
	break;
    case 'b':
	throw ExceptB();
	break;
    default:
	throw ExceptC();
    }
}

unsigned common;
unsigned do_A;
unsigned do_B;
unsigned do_UNK;

void test( int which ) {
    try {
	// exception prone code here, that may do a throw
	do_throw( which );
    } catch (...) {
	// common error code here
	++common;
	try {
	    throw;  // re-throw to more specific handler
	} catch (ExceptA&) {
	    // handle ExceptA here
	    ++do_A;
	} catch (ExceptB&) {
	    // handle ExceptB here
	    ++do_B;
	} catch (...) {
	    // handle unknown exceptions here
	    ++do_UNK;
	}
	throw;
    }
}

int main() {
    try { test( 'a' ); } catch( Except & ) {} catch( ... ) {_fail;}
    try { test( 'b' ); } catch( Except & ) {} catch( ... ) {_fail;}
    try { test( 'c' ); } catch( Except & ) {} catch( ... ) {_fail;}
    if( common != 3 ) _fail;
    if( do_A != 1 ) _fail;
    if( do_B != 1 ) _fail;
    if( do_UNK != 1 ) _fail;
    _PASS;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?