Know who is throwing exception

Answered

Is there any shortcut to know who is throwing an exception just by the catch? Like the hierarchy shortcut (ctrl+alt+h)?

try {
// code block
} catch (RuntimeException e) { <---

}
0
8 comments

When you place cursor on the catch keyword, IDE will show you the places which produce the related exception. The same does Main Menu | Edit | Find Usages | Find Usages in File action (Ctrl/Cmd+F7 default shortcut):

0

Thank you, Andrey. But the problem is if the exception is thrown inside some inner class.

0

With this action IDE shows all the places inside the try block where the exception might be thrown. What do you mean by inner class? Please provide a sample. Thanks.

0

Like this

try {
  ClassOne classOne = new ClassOne();
  classOne.doAny();
} catch (RuntimeExeption e) {
}

....

public class ClassOne {
  public void doAny() {
    ClassTwo classTwo = new ClassTwo();
    classTwo.doAny();
  }
}

....

public class ClassTwo {
  public void doAny() {
    throws RuntimeExeption();
  }
}

0

You throw the Runtime exception here. And do not have the throws clause in the method signature.

1. The method must have throws clause in its declaration when this method throws the checked exception.

2. Runtime exceptions are not checked exceptions that means that the compiler does not require that you handle the such an exception in a catch, or declare your method as throwing it.

0

But if the method contains the throws in method assignature in class ClassTwo, Intellij show the places which produce the related exception?

0

ClassOne.doAny() must contain the throws in the method signature if it throws the checked exception. Note that this works only for the checked exceptions.

0

Ok, only for checked exceptions. Thank you.

0

Please sign in to leave a comment.