如果将一个异常传递给Java的`System.out.println`,会发生什么?

huangapple 未分类评论41阅读模式
英文:

If you pass an exception into Java's `System.out.println`, what happens?

问题

在Java中,我们通常将字符串作为输入传递给`System.out.println`函数。
如果您尝试输入一些奇怪的内容,例如`Exception`类的一个实例,会发生什么呢?

    class Main {
        public static void main(String[] args]) {
            System.out.println("打印字符串是完全正常的");
            Exception e = new Exception();
            System.out.println(e);
        }
    }

哪些数据类型允许作为`System.out.println`的输入?
如果您尝试打印一个未为之重载的类的实例,会发生什么?
英文:

In java, we normally pass strings as input to System.out.println
What happens if you try to input something weird, such as an instance of the Exception class?

class Main {
    public static void main(String[] args]) {
        System.out.println("printing a string is perfectly normal");
        Exception e = new Exception();
        System.out.println(e);
    }
}      

What datatypes are allowed as input to System.out.println?
What happens if you attempt to print an instance of a class which System.out.println is not overloaded for?

答案1

得分: 0

这将调用带有Object参数的重载方法,其代码如下所示:

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
          print(s);
          newLine();
    }
}

如果对象为null,这实际上会打印"null",否则将打印调用对象的.toString方法的结果。

英文:

It calls the overloaded method with the Object parameter, which looks like this:

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
          print(s);
          newLine();
    }
}

This essentially prints "null" if the object is null and will print the result of calling .toString on the object otherwise.

答案2

得分: 0

什么数据类型可以作为 System.out.println 的输入?

任何类型。

如果您尝试打印一个没有为其重载 System.out.println 的类的实例会发生什么?

有一个针对 Object 的重载,它的文档解释了发生的情况:对于参数 x,会调用 String.valueOf(x),然后打印结果。

而如果您阅读该文档,它指出对于非空的 x,将调用 x.toString()

简而言之,所有对象都有一个可访问的 toString() 方法,这决定了打印的内容。

英文:

> What datatypes are allowed as input to System.out.println?

Anything.

> What happens if you attempt to print an instance of a class which
> System.out.println is not overloaded for?

There is an overload for Object, and its documentation says what happens: for the argument x, a call to String.valueOf(x) is made, and the result is printed.

And if you read the documentation for that, it says that x.toString()will be called for non-nullx.

In short, all objects have an accessible toString() method, and that is what determines what is printed.

huangapple
  • 本文由 发表于 2020年7月27日 06:11:25
  • 转载请务必保留本文链接:https://java.coder-hub.com/63106264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定