Exception handling

How to work with exception handling in Frida

**** NOTE: BLOG MOVED TO https://cmrodriguez.me/ ****

While working on Frida scripts it is usually common to get an error that will crash the script or even the application. So to reliably create applications powered by Frida it is advisable to protect the code from unexpected errors by using exceptions, as shown in the following example:

try {
    var instanceInnerClass = InnerClass.$new();
} catch (e) {
    var instanceOuterClass = OuterClass.$new();
    var instanceInnerClass = InnerClass.$new(instanceOuterClass);
} finally {
    //always gets to this part.
}

So if any error happens when you call the InnerClass.$new(), the script won't crash, and the execution will follow.

java exception handling from Frida

When an exception is thrown, Frida generates a javascript exception as well The variable thrown is a JSON with a $handle structure, so we have to cast it to an appropriate class. Depending on the situation we might or might not know which exception can be thrown based on the source code. So in order to handle all the possible exceptions thrown by Java, we need to cast it to a "java.lang.Throwable" class, and then cast it to the specific class (only if you want to do something specific related to the exception class):

var testExceptions = function () {
    var ThrowingExceptionClass = Java.use("com.blog.testfrida.exceptions.ThrowingExceptionClass");
    try {
        ThrowingExceptionClass.callException();
    } catch (ex) {
        //ex is a handle, you have to cast it.
        var Exception = Java.use("java.lang.Trowable");
        var item = Java.cast(ex,Exception);
        var SpecificException = Java.use(item.$className);
        item = Java.cast(ex,SpecificException);
        console.log(item.attribute.value);
    }

}

Last updated