用Java打印异常消息的3种不同方式

2021年3月21日17:23:42 发表评论 665 次浏览

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

java.lang.Throwable.printStackTrace()方法:

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

语法如下:

public void printStackTrace()
// 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.lang.ArithmeticException: / by zero
    at Test.main(Test.java:9)

输出如下:

java.lang.ArithmeticException: / by zero

toString()方法

:

通过使用此方法, 我们将仅获得异常的名称和描述。请注意, 此方法在Throwable类中被重写。

// 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

java.lang.Throwable.getMessage()方法:

通过使用此方法, 我们将仅获得异常的描述。

语法如下:

public String getMessage()
// 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

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

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