java - 如何在 Java 中访问自定义 Exception 类中的非构造函数方法?

标签 java exception

我在 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.

编辑:根据您的评论, printprintln 方法对于不同的参数可能会有不同的行为,如 here 所示,但是,对于非基本类型,行为是相同(即,当调用打印以控制台对象的 .toString() 方法时)。

关于java - 如何在 Java 中访问自定义 Exception 类中的非构造函数方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34530753/

相关文章:

java - 从 IntelliJ Idea 复制堆栈跟踪

java - 使用 Eclipse 创建新的 android 项目后,Eclipse 中的 SRC 文件夹为空(未创建 MainActivity 类)

java - 替换两个字符串之间的字符串

Java异常消息长度

c# - 下载大文件,保存在数据库中

asp.net - 超过最大请求长度 - 没有文件上传

java - 错误: method verifyCredentials in interface AccountService cannot be applied to given types

java - 泛型和通配符 : Java likes "new Foo<Bar<?>>"

Java 编码实践、运行时异常和此场景

java - hibernate "ManyToOne ... references an unknown entity"异常