java.lang.Throwable.getCause()方法实例

java.lang.Throwable.getCause()方法实例

width="728" height="90" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" id="aswift_0" name="aswift_0" style="box-sizing: border-box; left: 0px; position: absolute; top: 0px;">
id="iframeu1064372_0" src="http://pos.baidu.com/ockm?rdid=1064372&dc=2&di=u1064372&dri=0&dis=0&dai=1&ps=377x246&dcb=BAIDU_SSP_define&dtm=HTML_POST&dvi=0.0&dci=-1&dpt=none&tsr=0&tpr=1476164655511&ti=java.lang.Throwable.getCause()%E6%96%B9%E6%B3%95%E5%AE%9E%E4%BE%8B%20-%20java.lang&ari=2&dbv=2&drs=1&pcs=907x692&pss=978x1661&cfv=0&cpl=5&chi=1&cce=true&cec=UTF-8&tlm=1476164655&rw=709&ltu=http%3A%2F%2Fwww.yiibai.com%2Fjava%2Flang%2Fthrowable_getcause.html&ltr=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3D3W4yzl3fJ4OtMJTaZ5jb9QBZppYJ8cLphGgJWm_4wXPVK7DzrEcZtY4WRn2lPltjdM6U0DlQ1NBBa1XZM26LuFl2J9hKUaVJcZ_rbTJBITS%26wd%3D%26eqid%3Dc164818e0000a54c0000000557fc7c2c&ecd=1&psr=1920x1080&par=1920x1040&pis=-1x-1&ccd=24&cja=false&cmi=7&col=zh-CN&cdo=-1&tcn=1476164656&qn=1495bcb21fe3c5c6&tt=1476164655492.22.346.353" width="728" height="90" align="center,center" vspace="0" hspace="0" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true" style="box-sizing: border-box; border-width: 0px; border-style: initial; vertical-align: bottom; margin: 0px;">

Windows10用户联盟QQ群: 227270512


 java.lang.Throwable.getCause() 方法返回此抛出或空的原因,如果原因不存在或未知

声明

以下是java.lang.Throwable.getCause()方法的声明

public Throwable getCause()

参数

  • NA

返回值

此方法返回此抛出或空的原因,如果原因不存在或未知。

异常

  • NA

例子

下面的例子显示java.lang.Throwable.getCause()方法的使用。

package com.yiibai;

import java.lang.*;

public class ThrowableDemo {

   public static void main(String[] args) throws Throwable {

     try {
        newException();
     }
     catch(Throwable e) {
        System.err.println(e);
        // returns null as the cause is nonexistent or unknown.
        System.err.println("Cause = " + e.getCause());
     }
   }
  
   public static void newException() throws Exception {
      System.out.println("This is newException() function");
      throw new Exception("Exception...");
   }
}
 

让我们来编译和运行上面的程序,这将产生以下结果:

This is newException() function
java.lang.Exception: Exception...
Cause = null

### 关于 `java.util.concurrent.ExecutionException` 导致的 `ExceptionInInitializerError` 在 Java 编程中,`java.lang.ExceptionInInitializerError` 是一种特殊的运行时异常,它会在静态初始化器或类变量初始化过程中出现问题时被抛出。如果在这个阶段发生了任何未捕获的异常,则会触发此错误。 #### 1. **`ExecutionException` 的作用** `java.util.concurrent.ExecutionException` 是由并发包中的异步任务执行失败时抛出的一种受检异常。这种异常通常是由于底层的任务(如通过 `Future.get()` 方法获取的结果)引发了其他异常而产生的[^4]。 当 `ExecutionException` 被抛出并影响到某个类的静态初始化过程时,就会进一步引发 `ExceptionInInitializerError` 错误。 --- #### 2. **可能的原因** 以下是可能导致此类问题的一些常见原因: - 静态代码块或静态字段初始化期间尝试访问尚未完成加载的资源。 - 并发操作(如多线程环境下的 Future 执行)未能成功完成,并且其内部异常传播到了类初始化阶段。 - 使用了不恰当的方式处理外部依赖项,在这些依赖还未准备好之前即进行了强制调用[^3]。 例如,下面是一个典型的例子展示了如何因为 `ExecutionException` 引起 `ExceptionInInitializerError`: ```java public class Example { static { try { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(() -> { throw new RuntimeException(); }); String result = future.get(); // This will throw ExecutionException. } catch (InterruptedException | ExecutionException e) { System.err.println(e.getMessage()); } } public static void main(String[] args) { System.out.println("This line may never be reached."); } } ``` 上述程序将在启动时崩溃,并报告如下堆栈跟踪信息: ``` Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.util.concurrent.ExecutionException: java.lang.RuntimeException ... ``` --- #### 3. **解决方案** 针对这种情况可以采取以下措施来解决问题: ##### (1)改进异常处理逻辑 确保所有的潜在异常都被适当捕获而不至于中断整个应用程序的正常流程。可以通过修改静态初始器内的代码结构实现这一点。比如改写上面的例子为: ```java static { try { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(() -> "Success"); String result; try { result = future.get(); // Safely handle exceptions here. } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause instanceof RuntimeException) { System.err.println("Initialization failed due to runtime exception."); } else { throw new IllegalStateException(cause); } } } finally { // Ensure resources are cleaned up properly after use. } } ``` 这样即使出现了某些不可预见的情况也不会轻易破坏全局状态[^2]。 ##### (2)延迟初始化策略 考虑采用懒加载模式代替传统的即时加载方式。这意味着只有当真正需要用到该对象的时候才会去创建实例而不是一开始就定义好它们。这有助于减少不必要的复杂度以及降低风险水平[^1]。 例如利用双重锁定机制或者 Holder 类来进行单例设计: ```java private static class SingletonHolder { private final static MySingleton INSTANCE; static { try { INSTANCE = new MySingleton(); } catch (Throwable t) { throw new ExceptionInInitializerError(t); // Explicitly rethrow as needed. } } } public static MySingleton getInstance() { return SingletonHolder.INSTANCE; } ``` 这里我们将实际构造函数移到了一个单独的小型辅助类里边去了;这样一来即便第一次访问失败也仅仅意味着当前这一次请求得不到满足而已——后续还可以再次尝试直至成功为止。 --- ### 总结 通过对以上分析可以看出,要彻底消除由 `ExecutionException` 引发的 `ExceptionInInitializerError` ,就需要从根源上杜绝那些可能会干扰到类载入进程的因素存在 。具体做法包括但不限于加强局部防护力度、调整整体架构布局等方面的工作。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值