Skip to content

CWrapCatch

Lenni0451 edited this page Mar 17, 2024 · 1 revision

The CWrapCatch annotation is used to wrap a catch block around a method or method call.
The catched exception can be specified using the parameter of the transformer method.

Method signature

The transformer method needs to have one parameter which represents the exception to catch.
The return type of the transformer method needs to be the same as the return type of the target method.
When injecting into a static method, the transformer method also needs to be static and vice versa.

//Injecting into a static method
@CWrapCatch(...)
public static ReturnType transform(final Exception e)

//Injecting into a non-static method
@CWrapCatch(...)
public ReturnType transform(final Exception e)

Targets

If an entire method should be wrapped, the target field of the CWrapCatch annotation should be empty.
To specify a method call to wrap, you need to specify the method pattern in the target of the annotation (see Targets for more information).
When a method call is found multiple times, the ordinal field can be used to choose the target.
Also, check out CSlice for more information about how slices work.

Targeting multiple methods

The value field can be an array of strings to target multiple methods.
The transformer method needs to be compatible with all targeted methods.

@CWrapCatch(value = {"method1", "method2"})
public void transform(final Exception e)

Examples

Original method:

public int method(final String s1, final String s2) {
    int i1 = Integer.parseInt(s1);
    int i2 = Integer.parseInt(s2);
    return i1 + i2;
}

Wrapping the entire method

Transformer method:

@CWrapCatch("method")
public int transform(final NumberFormatException e) {
    return 0;
}

Injected code:

public int method(final String s1, final String s2) {
    try {
        int i1 = Integer.parseInt(s1);
        int i2 = Integer.parseInt(s2);
        return i1 + i2;
    } catch (NumberFormatException e) {
        return this.transform(e);
    }
}

Wrapping a method call

Transformer method:

@CWrapCatch(value = "method", target = "Ljava/lang/Integer;parseInt(Ljava/lang/String;)I")
public int transform(final NumberFormatException e) {
    return 0;
}

Injected code:

public int method(final String s1, final String s2) {
    int i1;
    try {
        i1 =  = Integer.parseInt(s1);
    } catch (NumberFormatException e) {
        i1 = this.transform(e);
    }
    int i2;
    try {
        i2 = Integer.parseInt(s2);
    } catch (NumberFormatException e) {
        i2 = this.transform(e);
    }
    return i1 + i2;
}