我在 Java 中搜索自定义异常时遇到了以下代码。
class MyException extends Exception{
String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("Output String = "+str1) ;
}
}
public class CustomException{
public static void main(String args[]){
try{
throw new MyException("Custom");
} catch(MyException exp) {
System.out.println("This is catch block") ;
System.out.println(exp) ;
}
}
}
它的输出是:
这是 catch block
输出字符串=自定义
但是我无法理解如何调用 MyException 类的 toString() 方法。 谁能给我解释一下吗?
最佳答案
将项目打印到控制台时,所提供对象的 .toString()
方法会在 println
方法或其任何依赖项中自动调用,根据 documentation :
public void println(Object x)
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
Parameters:
x - The Object to be printed.
编辑:根据您的评论, print
和 println
方法对于不同的参数可能会有不同的行为,如 here 所示,但是,对于非基本类型,行为是相同(即,当调用打印以控制台对象的 .toString()
方法时)。
关于java - 如何在 Java 中访问自定义 Exception 类中的非构造函数方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34530753/