Java Exception 里的 target怎么取到并打印出来
时间: 2024-02-20 11:58:49 浏览: 22
在 Java 中,可以使用 `try-catch` 语句来捕获异常并访问异常对象。异常对象包含有关发生异常的详细信息,包括异常类型、异常消息和堆栈跟踪信息等。要访问异常对象中的信息,可以使用 `catch` 语句后面的参数来指定一个变量名,然后使用该变量名来引用异常对象。
以下是一个示例代码,演示如何捕获异常并打印异常对象中的信息:
```java
try {
// code that may raise an exception
int target = 1 / 0;
} catch (Exception e) {
// handle the exception
System.out.println("Exception Type: " + e.getClass().getName());
System.out.println("Exception Message: " + e.getMessage());
System.out.println("Exception Target: " + e.toString());
}
```
在上面的代码中,`target` 是一个除以零的操作,会引发 `ArithmeticException` 异常。在 `catch` 语句中,我们使用 `e` 参数来引用异常对象,然后使用 `getClass()` 方法和 `getMessage()` 方法分别获取异常类型和异常消息。最后,我们使用 `toString()` 方法获取异常对象的字符串表示形式,其中包含有关异常的详细信息。
当运行上面的代码时,它将输出以下内容:
```
Exception Type: java.lang.ArithmeticException
Exception Message: / by zero
Exception Target: java.lang.ArithmeticException: / by zero
```
注意,异常对象中的信息可能因异常类型而异,因此您需要根据实际情况访问异常对象中的不同属性来获取更多信息。