gpt4 book ai didi

java - 类型中的方法不适用于参数 (Class
)?

转载 作者:行者123 更新时间:2023-12-02 12:11:38 24 4
gpt4 key购买 nike

我想要做的是打印一条自定义错误消息,该消息会打印错误导致的类和函数。要获取该类,我使用 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)

而且我不知道为什么无法使用 .classClass 传递到函数中。 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

In java class is a keyword, So you can't declare like a variable, i.e Change Class class to Class c or any

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com