# Exception handling

\*\*\*\* **NOTE: BLOG MOVED TO** [**https://cmrodriguez.me/**](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:

```javascript
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):

```javascript
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);
    }

}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://neo-geo2.gitbook.io/adventures-on-security/frida-scripting-guide/exception-handling.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
