我要执行的操作是打印一条自定义错误消息,该消息将打印导致错误的类和函数。要获取该类,请使用getClass()。但是,当我尝试运行我的项目时,出现以下错误消息:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    The method printException(Exception) in the type ExceptionPrinter is not applicable for the arguments (FileNotFoundException, Class<Main>, String, String)
    The method printException(Exception) in the type ExceptionPrinter is not applicable for the arguments (ParseException, Class<Main>, String, String)

    at Main.main(Main.java)
而且我不知道为什么我不能使用Class.class传递给函数。我之前的B/c:
ExceptionHandler.printException(e, getClass() + " main() could not find input file");
ExceptionPrinter.java printException()如下所示:
public static void printException(Exception e, String message){
    System.err.println(message);
    printException(e);
}
而且效果很好。
如果有人可以帮助我,以便我可以将类名称传递给我的ExceptionPrinter.java,那就太好了!

Main.java
public class Main {

    public static void main(String[] args) {

        try {
            ...

        } catch (FileNotFoundException e) {
            ExceptionPrinter.printException(e, Main.class, "main", "Input file not found");
        } catch (ParseException e) {
            ExceptionPrinter.printException(e, Main.class, "main", "Exception occurred during parsing");
        }
    }

}
ExceptionPrinter.java
public class ExceptionPrinter {

    public static void printException(Exception e){
        System.err.println("Error message: " + e.getMessage());
        e.printStackTrace();
    }

    public static void printException(Exception e, Class class, String function, String message){
        System.err.println(class + " " + function + "(): " + message);
        printException(e);
    }

}

最佳答案

Main.java

public class Main {
    public static void main(String[] args) {
        try {
            int a=2/0;
        } catch (ArithmeticException e) {
            ExceptionPrinter.printException(e, Main.class, "main", "Input file not found");
        } catch (NullPointerException e) {
            ExceptionPrinter.printException(e, Main.class, "main", "Exception occurred during parsing");
        }
    }

}

ExceptionPrinter.java


public class ExceptionPrinter {

    public static void printException(Exception e){
        System.err.println("Error message: " + e.getMessage());
        e.printStackTrace();
    }

    public static void printException(Exception e, Class c, String function, String message){
        //System.err.println(class + " " + function + "(): " + message);
        printException(e);
    }
}

关于java - 类型中的方法不适用于参数(Class <Main>)吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46508648/

10-11 22:25
查看更多