Topic: 技巧--throw exception

  Print this page

1.技巧--throw exception Copy to clipboard
Posted by: Jove
Posted on: 2004-09-14 20:35

001 import java.lang.reflect.Field;
002 import java.sql.SQLException;
003 import sun.misc.Unsafe;
004 
005 public class TestException {
006 
007   public static void main(String[] args) {
008     TestException me = new TestException();
009     try {
010       me.foo();
011       if (false) {
012         //never happen
013         throw new SQLException();
014       }
015     } catch (SQLException e) {
016       e.printStackTrace();
017     }
018 
019   }
020   public static Unsafe getUnsafe() {
021     try {
022       Field field = Unsafe.class.getDeclaredField("theUnsafe");
023       field.setAccessible(true);
024       return (Unsafe) field.get(null);
025     } catch (Exception ex) {
026       throw new RuntimeException("can't get Unsafe instance");
027     }
028   }
029 
030   private void foo() {
031     getUnsafe().throwException(new SQLException("test"));
032   }
033 }

出处 http://www.oreillynet.com/pub/wlg/5559

2.Re:奇技淫巧--throw exception [Re: Jove] Copy to clipboard
Posted by: href
Posted on: 2004-09-15 09:45

没看明白,楼主能否简单解释一下?

3.Re:奇技淫巧--throw exception [Re: Jove] Copy to clipboard
Posted by: siage
Posted on: 2004-09-16 12:03

楼主自己编的Exception?

4.Re:奇技淫巧--throw exception [Re: href] Copy to clipboard
Posted by: Jove
Posted on: 2004-09-16 14:56

href wrote:
没看明白,楼主能否简单解释一下?


background是这样
在error handling时,我们可以选择抛出checked exception,或是runtime exception
如果一个方法throws checked exception,则调用者必须显式的try/catch,
而runtime exception在不少情况下,我们并不能对异常作多少善后处理,
所以会try/catch常常是e.printStaceTrace,logging,rethrown
因此,越来越多api倾向与抛出runtimeexception,如SpringFramework,
SpringFramework甚至可以把SQLException,HibernateException等 checked exception,包装成runtime exception

但是如果我们在遇到SQLException时,把它包装成runtime exception,
外面的代码就不能使用try{..}catch(SQLException e){..}来对数据库异常作相应的处理。
我们可以能需要创建很多自己的包装类,或是在Runtimeexception中放入exception code等处理

本文提到的方法,可以结合两者的好处
使用Unsafe类来抛出异常,由于没有使用throw 关键字,所以Java编译器不认为这个方法抛出异常。所以就像使用RuntimeException一样使用
但是在调用方法的地方,你依然可以catch(SQLException e), 当然为了骗过编译器,你需要写一些类似if(false){throw new SQLException());的代码,否则编译器不会允许你catch永远不会出现的异常

Unsafe类是个SUN JDK的一个类,作者使用反射,得到其引用。 Unsafe类正如其名,可以作很多危险的事情,如分配内存 //汗

这里贴这个,不表示这是种好的方法,只是告知大家,多一种选择,甚至作为消遣 Big Smile

5.Re:奇技淫巧--throw exception [Re: Jove] Copy to clipboard
Posted by: littledeer1974
Posted on: 2004-09-22 10:21

(建议修改贴名,纯属个人感受)


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923