---
title: "Netty中PlatformDependent绕开受检查异常处理"
author: "jnullpointer"
date: "2014-09-10T14:07:11Z"
tags: []
categories: ["编程语言"]
slug: "netty-platformdependent"
draft: false
lastmod: "2014-09-13T22:45:46Z"
id: 2114658
url: "https://jnullpointer.iteye.com/blog/2114658"
---

Netty是个值得花时间学习的框架，即使一个不起眼的程序，都有值得深入学习的地方。比如：io.netty.util.internal.PlatformDependent类中，对异常的处理就非常巧妙。
经常会碰到这种情况，实现一个接口，接口签名是没有申明异常的。但在实现中却需要捕获异常。比如：guava包中的通用接口

```java

    public interface Supplier<T> {
      /**
       * Retrieves an instance of the appropriate type. 
       * The returned object may or
       * may not be a new instance, depending on the implementation.
       *
       * @return an instance of the appropriate type
       */
      T get();
    }

```

我们实现这个接口，假设需要调用JDBC接口获取数据库的数据：

```java

    public class JdbcSupplier implements Supplier<Map> {
        Map get() {
            try {
                //调用JDBC接口
                   //封装数据，return
              } catch (SQLException e) {
                throw new RuntimeException (e); 
            }
        }
    }  

```

我们不得不捕获异常，并转换为RuntimeException，才能编译通过，但丢失了最初的异常面目。这类问题一般有两种做法。就像PlatformDependent类的throwException方法。
1.利用sun.misc.Unsafe的throwException方法；
2.利用泛型的擦拭，Raises an exception bypassing compiler checks for checked exceptions

```java

    public static void throwException(Throwable t) {
        if (hasUnsafe()) {
            PlatformDependent0.throwException(t);
        } else {
            //显式指定异常为RuntimeException，欺骗编译器通过编译；
              //编译后会擦拭掉泛型信息，变成具体的受检查异常；
            PlatformDependent.<RuntimeException>throwException0(t);
        }
    }
    
    static void throwException(Throwable t) {
        UNSAFE.throwException(t);
    }

    @SuppressWarnings("unchecked")
    private static <E extends Throwable> void throwException0(Throwable t) throws E {
        throw (E) t;
    }

```