1

I have a java file and I want to get the exception message for the exception type after the throw keyword

 // this is the code of D:\\ProjectFile\\AST\\Test\\000001\\test.java
 if (len < 0 || offset < 0 || len + offset > b.length) {
            String str = "index out of bounds";
            throw new IndexOutOfBoundsException(s);
        }

For example, I want to get the string, "index out of bounds" inthe "D:\ProjectFile\AST\Test\000001\test.java", because he is a property of IndexOutOfBoundsException

So, When I use spoon, I don't find enough examples to teach me


public static void main(String[] args) {
    Launcher launcher = new Launcher();

    launcher.addInputResource("D:\\ProjectFile\\AST\\Test\\000001\\test.java");

    launcher.buildModel();
    CtModel model = launcher.getModel();


    List<CtThrow> throwList = model.getElements(new TypeFilter<>(CtThrow.class));

    for (int i = 0; i < throwList.size();i++) {
        System.out.println(throwList.get(i).getThrownExpression());
    }
}

Using the code above, I can only get the following:

new java.lang.IndexOutOfBoundsException(s)

I can not get the value of s.

I want to be able to check the constructor of this exception type and get its property value, how should I do this?

Link
  • 19
  • 2

2 Answers2

0

try it :

 IndexOutOfBoundsException e  = new java.lang.IndexOutOfBoundsException(s);
        Field[] field = e.getClass().getDeclaredFields();
        for(int i = 0 ; i<field.length ; i++)
            java.lang.System.out.print(field[i].get(e));

But it won't be able to get the value declared as private

lavantho0508
  • 125
  • 10
  • thanks so much, but it doesn't seem to work for me. Error message says `IndexOutOfBoundsException` is private static. I want to parse a java file by spoon and get the exception message in the java file, it doesn't seem to fit my scenario? – Link Nov 14 '22 at 10:49
  • ok bro , it not work private field – lavantho0508 Nov 14 '22 at 10:50
0

You need some kind of data-flow analysis for this.

In Spoon, this is not in spoon-core but in submodule https://github.com/INRIA/spoon/tree/master/spoon-dataflow

Martin Monperrus
  • 1,845
  • 2
  • 19
  • 28