java.lang.ExceptionInInitializerError原因及解决办法

java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.LinkageError
java.lang.ExceptionInInitializerError

ExceptionInInitializerError 通常意味着在静态初始化块或静态变量初始化过程中发生了异常。

静态代码块异常:如果在静态代码块中有任何异常抛出,都会导致此错误。

public class StaticBlock {

    private static int state;

    static {
        state = 42 / 0; //除0异常
    }
}

静态变量初始化异常:如果静态变量在初始化时抛出了异常,也会导致此错误。(编译后实际上也是在静态代码块里面)

public class Example {
    private static final int number = Integer.parseInt("abc"); // 这里会抛出NumberFormatException
}

解决方法

一般来说,查看堆栈跟踪都能找出问题所在。

  1. 检查静态初始化块:确保静态初始化块中没有抛出异常的代码。
  2. 检查静态变量初始化:确保所有静态变量的初始化都是安全的,没有抛出异常。

工作中的例子

java.lang.ExceptionInInitializerError at com.xxx.xx.Service.onInit(Service.java:654) 

查看654行代码,引用了一个静态类。

static {
    try {
        String path = "/data/data/com.xxx.xx/lib/libxxplay.so";
        File file = new File(path);
        if (file.exists()) {
            SFLogger.d(TAG, "use /data/data/com.xxx.xx/lib/libxxplay.so");
            System.load(path);
        } else {
            SFLogger.d(TAG, "use /system/lib/libxxplay.so");
            System.loadLibrary("xxplay");
        }
    } catch (Exception e) {
        SFLogger.e(TAG, "JniUtil loadLibrary exception = " + e.getMessage());
    }
}

以上代码咋一看好像也没什么问题啊,异常都catch住了。

但如果仔细研究就会发现,这里的问题是滥用了Exception,没有针对具体异常进行捕获。查看loadLibrary源码发现其可能会抛出SecurityExceptionUnsatisfiedLinkError或者NullPointerExceptionSecurityExceptionNullPointerException的父类都是RuntimeException,是一种异常(Exception),UnsatisfiedLinkError的父类是LinkageError,是一种错误(Error),所以如果这里发生了UnsatisfiedLinkError,通过Exception是捕获不了的,必须通过他们的共同父类Throwable来进行捕获。当然,最好还是针对具体的异常进行捕获,不要用这种扩大化的捕获方式,容易隐藏问题。

    /**
     * Loads the native library specified by the <code>libname</code>
     * argument.  The <code>libname</code> argument must not contain any platform
     * specific prefix, file extension or path. If a native library
     * called <code>libname</code> is statically linked with the VM, then the
     * JNI_OnLoad_<code>libname</code> function exported by the library is invoked.
     * See the JNI Specification for more details.
     *
     * Otherwise, the libname argument is loaded from a system library
     * location and mapped to a native library image in an implementation-
     * dependent manner.
     * <p>
     * The call <code>System.loadLibrary(name)</code> is effectively
     * equivalent to the call
     * <blockquote><pre>
     * Runtime.getRuntime().loadLibrary(name)
     * </pre></blockquote>
     *
     * @param      libname   the name of the library.
     * @exception  SecurityException  if a security manager exists and its
     *             <code>checkLink</code> method doesn't allow
     *             loading of the specified dynamic library
     * @exception  UnsatisfiedLinkError if either the libname argument
     *             contains a file path, the native library is not statically
     *             linked with the VM,  or the library cannot be mapped to a
     *             native library image by the host system.
     * @exception  NullPointerException if <code>libname</code> is
     *             <code>null</code>
     * @see        java.lang.Runtime#loadLibrary(java.lang.String)
     * @see        java.lang.SecurityManager#checkLink(java.lang.String)
     */
    @CallerSensitive
    public static void loadLibrary(String libname) {
        Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
    }

参考

ExceptionInInitializerError | Android Developers

When Does Java Throw the ExceptionInInitializerError? | Baeldung

Chapter 11. Exceptions

### java.lang.ExceptionInInitializerError原因及解决方案 #### 1. 异常的原因 `java.lang.ExceptionInInitializerError` 是一种特殊的 `Error` 类型,在 Java 静态初始化阶段发生。当类的静态变量、静态代码块或枚举常量在初始化时抛出未捕获的异常,JVM 将触发此错误[^1]。 这种错误的根本原因是底层发生了某种异常(通常是运行时异常),而这些异常未能被适当处理。例如: - 文件读取失败导致 `NullPointerException` 或者 `FileNotFoundException`。 - 数据库连接池配置不正确引发 `SQLException`。 - 属性文件加载失败引起 `IOException`。 #### 2. 解决方案详解 ##### (1)检查静态初始化逻辑 确保静态代码块内的操作不会抛出任何未经处理的异常。可以通过增加异常捕获机制来防止此类问题的发生。例如: ```java static { try { FileInputStream is = new FileInputStream("config.properties"); Properties properties = new Properties(); properties.load(is); } catch (Exception e) { System.err.println("Failed to initialize static resources: " + e.getMessage()); throw new RuntimeException(e); } } ``` 上述代码片段展示了如何通过捕获潜在的异常并将其转换为受控形式的方式减少 `ExceptionInInitializerError` 发生的可能性[^3]。 ##### (2)验证资源配置路径 如果问题是由于无法找到外部资源(如属性文件或数据库驱动程序)引起的,则需确认相关文件的位置是否正确。常见的情况包括但不限于: - **文件缺失**:目标文件可能不存在于指定路径下。 - **构建过程丢失**:即使源码中有配置文件,但在打包成 JAR 后可能会遗失。 针对这些问题可以采取如下措施: - 确认配置文件位于项目的 `src/main/resources` 路径下以便自动包含至最终产物中。 - 如果手动指定了绝对路径,请改为相对路径或者使用 ClassLoader 加载资源: ```java InputStream inputStream = getClass().getClassLoader().getResourceAsStream("servletDemo.properties"); if (inputStream != null) { prop.load(inputStream); } else { throw new FileNotFoundException("Property file not found."); } ``` 这段代码利用了 `ClassLoader.getResourceAsStream()` 方法动态获取嵌入式的属性文件,从而规避硬编码路径带来的风险[^4]。 ##### (3)重启环境与清理缓存 有时尽管一切设置看似无误但仍持续遭遇同样的错误消息。此时不妨考虑以下建议: - 清理 IDE 缓存以及重建项目; - 关闭再启动应用服务器(Tomcat/Jetty 等); - 删除旧版编译输出重新生成最新版本; 简单来说,“冷启动”往往能消除一些难以追踪的状态残留所造成的干扰[^4]。 #### 3. 示例代码修正对比 以下是基于前述讨论的一个改进后的完整例子: ```java public class DruidUtils { private static final DataSource DATASOURCE; static { InputStream stream = null; Properties props = new Properties(); try { // 使用 ClassLoader 来定位资源文件 stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("servletDemo.properties"); if (stream == null) { throw new IOException("Unable to locate property file 'servletDemo.properties'."); } props.load(stream); DATASOURCE = DruidDataSourceFactory.createDataSource(props); } catch (Exception ex) { throw new IllegalStateException("Initialization of data source failed.", ex); } finally { if (stream != null) { try { stream.close(); } catch (IOException ignored) {} } } } public static Connection getConnection() throws SQLException { return DATASOURCE.getConnection(); } } ``` 以上实现不仅增强了健壮性还提高了可维护性和移植能力[^2]。 --- 问题
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值