Exception implementation

zhaozj2021-02-16  69

According to I know, there are 2 methods, dynamics and static

Dynamic is the compiler to help you insert a bunch of code (the key code is setjmp and

Longjmp), insert these codes in each of your Throw catch, will

Impact overall performance (this can be achieved without what system related things)

Static is to generate an Expection Handler lookup table, then each time

When you leave, check it to check it. If there is no abnormal situation, this way

Low expenditure, but this is related to the operating system, if the virtual machine is

. . .嘿嘿.

Then, simply talk about the dynamic method, my specific code lazy write (in fact, I can't write)

Give a pseudo code:

Struct exception {

Char * name;

INT TYPECODE;

//... Porthers

}

INT hashfun (char *) // This function makes the string into int, the only corresponding

{...}

Exception * createException (char * name) // Create a new EXCEPTION

{..}

Void FreeException (Exception *) // Destroy it!

{..}

/ / -------------------------------------------------------------------------------------------- ------------

Struct ExceptionHandler

{

INT TYPECODE;

JMP_BUF Location; // This is more important. . .

}

Struct ExceptionHandlerstack

{Int size; // Now the size of List

ExceptionHandler List [MAX]; // A Handler's chain

ExceptionHandlerstack (); // Initialization

~ ExceptionHanclerstack (); // destroyed work. . .

Static ExceptionHandler * push (char * name) // According to Name, use the Hash function to generate Typecod

E, then fill in the last handler in the chain, then return it

Static pop (); //. . . It is clear

Static void throwexception (Exception * EX) // Throw an exception

{

Find in the chain, find Typecode, the same handler

Longjmp (List [size] .location, (int) ex); // key function. . .

}

}

The basic achievement is similar, then the code is inserted into the compiler.

Originally:

Void fun ()

{

Try {

EXCETPION * EX;

EX = CREATEEXCEPTION ("Name");

ThrowException (EX);

} catch (Exception * EX)

{

DOSMETHING (EX);

}

Ok, the compiler is changed. . .

Void fun ()

{

ExceptionHandler * HD;

int R;

HD = ExceptionHandlerList :: Push ("name");

Ret = setjmp (hd-> location);

IF (RET == 0)

{EXCETPION * EX;

EX = CreateException ("Name);

ExcetPionHandlerList :: throwexception (ex);

Else

{EXCEPTION * EX;

EX = (Exception *) Ret;

DOSMETHING (EX); FreeException (EX);

}

ExceptionHanclerList :: POP (HD);

}

转载请注明原文地址:https://www.9cbs.com/read-16721.html

New Post(0)