sleske
sleske

Reputation: 83609

In Eclipse, how can I find Java code that throws a certain Exception?

When trying to understand Java code, I sometimes want to find all code where a certain custom exception (i.e. a subclass of java.lang.Exception) is being thrown.

To do this, in Eclipse I can use "Find References" on the Exception class. However that finds both places that throw and places that catch the exception.

Is there a way to specifically find code that throws a certain exception?


Related question: Eclipse: find lines in a block that can throw exceptions

However, that question is about finding all places in a single block of code, while my question is about finding all places across multiple classes of a project.

Upvotes: 1

Views: 2046

Answers (3)

Grim
Grim

Reputation: 1976

Assuming we are not talking about indirect throws like a NPE or ClassCastException, and assuming we throw a Exception right where we create the exception, you can invoke the call hierarchy of the Exception's constructor.

Eclipse's "Call Hierarchy" can not only be used on methods, but also on classes - then it will show all constructor invocations. Use the Call Hierarchy on the Exception class to find constructor invocations even in 3rd level librarys.

Upvotes: 1

luk2302
luk2302

Reputation: 57114

In IntelliJ you can do a so called "Structural Search". Using this Structural Search for "new A()" does find all the 3 instantiations used below:

private static class A { }

public static void main(String[] args) {
    new A();

    new

            A();

    new    A(


    );
}

enter image description here

https://www.quora.com/How-can-IntelliJ-style-Structural-Search-and-Replace-be-done-on-Eclipse hints at doing the same in Eclipse by doing a "simple" search with regex and using \W wherever possible inside the regex expression to "ignore" line breaks, whitespaces, tabs, etc. new(\W+)A(\W*)\( actually works quite well.

I know this is not a full answer, but maybe you can find out more knowing the term that IntelliJ uses for this purpose

Upvotes: 1

sleske
sleske

Reputation: 83609

This is possible by using the "Java Search", and limiting the matches to instance creations.


Instructions:

  • open the "Java Search" (menu "Search"/"Java...", or toolbar icon)
  • as the search term, enter the fully qualified name of the exception you are looking for
  • "Search for": "Type"
  • "Limit To": "Match locations", then in the linked detail selection, select only "Class instance creations"

Two limitations:

  • This will also find code that creates an exception without throwing it (unusual, but possible).
  • This will not find code that catches and then rethrows an exception - which may or may not be what you want.

Inspired by the similar Eclipse bug 296947.

Upvotes: 2

Related Questions