📜  在Java中打印异常消息的不同方法

📅  最后修改于: 2022-05-13 01:54:34.506000             🧑  作者: Mango

在Java中打印异常消息的不同方法

在Java中,有三种打印异常信息的方法。它们都存在于 Throwable 类中。由于 Throwable 是所有异常和错误的基类,我们可以在任何异常对象上使用这三个方法。

Java中打印异常的Java

在Java中有三种打印异常消息的方法。这些都是:

1. Java.lang.Throwable.printStackTrace() 方法:

通过使用此方法,我们将获得以冒号分隔的异常的名称(例如Java.lang.ArithmeticException)和描述(例如 / 由零),以及堆栈跟踪(其中代码,该异常已发生)在下一行。

句法:

public void printStackTrace()
Java
// Java program to demonstrate
// printStackTrace method
  
public class Test {
    public static void main(String[] args)
    {
        try {
            int a = 20 / 0;
        }
        catch (Exception e) {
            // printStackTrace method
            // prints line numbers + call stack
            e.printStackTrace();
  
            // Prints what exception has been thrown
            System.out.println(e);
        }
    }
}


Java
// Java program to demonstrate
// toString  method
  
public class Test {
    public static void main(String[] args)
    {
        try {
            int a = 20 / 0;
        }
        catch (Exception e) {
            // toString method
            System.out.println(e.toString());
  
            // OR
            // System.out.println(e);
        }
    }
}


Java
// Java program to demonstrate
// getMessage method
  
public class Test {
    public static void main(String[] args)
    {
        try {
            int a = 20 / 0;
        }
        catch (Exception e) {
            // getMessage method
            // Prints only the message of exception
            // and not the name of exception
            System.out.println(e.getMessage());
  
            // Prints what exception has been thrown
            // System.out.println(e);
        }
    }
}


运行时异常:

java.lang.ArithmeticException: / by zero
    at Test.main(Test.java:9)

输出:

java.lang.ArithmeticException: / by zero

2. toString() 方法

使用此方法只会获取异常的名称和描述。请注意,此方法在 Throwable 类中被覆盖。

Java

// Java program to demonstrate
// toString  method
  
public class Test {
    public static void main(String[] args)
    {
        try {
            int a = 20 / 0;
        }
        catch (Exception e) {
            // toString method
            System.out.println(e.toString());
  
            // OR
            // System.out.println(e);
        }
    }
}
输出
java.lang.ArithmeticException: / by zero

3. Java.lang.Throwable.getMessage() 方法:

使用这种方法,我们只会得到一个异常的描述。

句法:

public String getMessage()

Java

// Java program to demonstrate
// getMessage method
  
public class Test {
    public static void main(String[] args)
    {
        try {
            int a = 20 / 0;
        }
        catch (Exception e) {
            // getMessage method
            // Prints only the message of exception
            // and not the name of exception
            System.out.println(e.getMessage());
  
            // Prints what exception has been thrown
            // System.out.println(e);
        }
    }
}
输出
/ by zero