private static @Nullable PsiMethod collectExceptions(Set<? super PsiClassType> unhandled, PsiElement element) {
    PsiElement targetElement = null;
    PsiMethod targetMethod = null;

    final PsiElement psiElement;
    if (element instanceof PsiMethodReferenceExpression) {
      psiElement = element;
    }
    else {
      PsiElement parentStatement = CommonJavaRefactoringUtil.getParentStatement(element, false);
      if (parentStatement instanceof PsiDeclarationStatement declaration) {
        PsiElement[] declaredElements = declaration.getDeclaredElements();
        if (declaredElements.length > 0 && declaredElements[0] instanceof PsiClass) {
          return null;
        }
      }

      psiElement = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, PsiMethod.class);
    }
    if (psiElement instanceof PsiFunctionalExpression) {
      targetMethod = LambdaUtil.getFunctionalInterfaceMethod(psiElement);
      targetElement = psiElement instanceof PsiLambdaExpression lambda ? lambda.getBody() : psiElement;
    }
    else if (psiElement instanceof PsiMethod method) {
      targetMethod = method;
      targetElement = psiElement;
    }

    if (targetElement == null || targetMethod == null) return null;
    if (!ExceptionUtil.canDeclareThrownExceptions(targetMethod)) return null;
    List<PsiClassType> exceptions = getUnhandledExceptions(element, targetElement, targetMethod);
    if (exceptions == null || exceptions.isEmpty()) return null;
    unhandled.addAll(exceptions);
    return targetMethod;
  }
private static @Nullable PsiMethod collectExceptions(Set<? super PsiClassType> unhandled, PsiElement element)