理解error和exception之間的區別

不少程序員不清楚error和exception之間的區別,這區別對於如何正確的處理問題而言很是重要(見附1,「簡要的敘述error和exception」)。就像Mary Campione的「The Java Tutorial」中所寫的:「exception就是在程序執行中所發生的中斷了正常指令流的事件(An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.)。」依照美國傳統辭典(American Heritage Dictionary)所解釋的,error就是:「效果或狀況背離了可接受的通常法則(The act or an instance of deviating from an accepted code of behavior.)」



背離(deviation)、中斷(disruption),有什麼區別呢?讓咱們來這樣想:若是你驅車在公路上行駛時有人攔住了你,這就叫作「中斷」。若是車根本就沒法發動,那就叫作「背離」。

這與Java有什麼關係呢?不少。Java中有一個至關有趣的error和exception的結構。

是的,很是正確:全部使用try{} catch(Exception e){}的代碼塊只能找到你一半的錯誤。可是,是否try並catch Throwable取決於你捕捉它的緣由。快速的看一下Error的子類,它們的名字相似VirtualMachineError,ThreadDeath,LinkageError。當你想捕獲這些傢伙們的時候,你要肯定你須要捕獲它們。由於那些都是很嚴重的錯誤。

可是ClassCastException是一個error嗎?不徹底是。ClassCastException或任何類型的exception只是虛擬機(VM,VirtualMachine)讓你知道有問題發生的方式,這說明,開發者產生了一個錯誤,如今有一個機會去修正它。

另外一方面,error是虛擬機的問題(一般是這樣,但也多是操做系統的問題)。引用Java文檔中關於error的說明:「Error是Throwable的子類,它的出現說明出現了嚴重的問題。通常應用程序除非有理由,不然不該該捕捉Error。一般這是很是反常的狀況。」

因此,error很是強大,並且但處理它遠比通常開發者想象的要難(固然不是你)。若是你在作一項很簡單的工做的話,你認爲有必要去處理error?

首先,記住,error跟exception拋出的方式大致相同的,只有一點不一樣。就是一個拋出error的方法不須要對此進行聲明(換句話說,這是一個unchecked exception(也被稱作Runtime Exception))。


Java代碼  收藏代碼

    public void myFirstMethod() throws Exception  
      
        //Since it's an exception, I have to declare   
      
        //it in the throws clause {  
      
        throw new Exception();  
      
    }  
      
       
      
    public void mySecondMethod()  
      
        //Because errors aren't supposed to occur, you   
      
        //don't have to declare them.   
      
    {  
      
        throw new Error();  
      
    }  




注意,有一些exception是不可控制的(unchecked exception),跟error的表現是同樣的,如:NullPointerException,ClassCastException和IndexOutOfBoundsException,它們都是RuntimeException的子類。RuntimeException和其子類都是unchecked excception。



那應該如何處理這些使人討厭的unchecked exception呢?你能夠在可能出現問題的地方catch它們,但這只是一個不完整的解決方法。這樣雖然解決了一個問題,但其他的代碼仍可能被其餘unchecked exception所中斷。這裏有一個更好的辦法,感謝ThreadGroup類提供了這個很棒的方法:



Java代碼  收藏代碼

    public class ApplicationLoader extends ThreadGroup  
      
    {  
      
         private ApplicationLoader()  
      
         {  
      
              super("ApplicationLoader");  
      
         }  
      
       
      
         public static void main(String[] args)  
      
         {  
      
              Runnable appStarter = new Runnable()  
      
              {  
      
                   public void run()  
      
                   {  
      
                        //invoke your application  
      
                        (i.e. MySystem.main(args)  
      
    }  
      
              }  
      
              new Thread(new ApplicationLoader(), appStarter).start();  
      
         }  
      
       
      
         //We overload this method from our parent  
      
         //ThreadGroup , which will make sure that it  
      
         //gets called when it needs to be.  This is   
      
         //where the magic occurs.  
      
    public void uncaughtException(Thread thread, Throwable exception)  
      
         {  
      
              //Handle the error/exception.  
      
              //Typical operations might be displaying a  
      
              //useful dialog, writing to an event log, etc.  
      
         }  



這個技巧太棒了。想一想這種狀況,你對你的GUI程序進行了修改,而後一個unchecked exception被拋出了。而且你的GUI程序經常具備了錯誤的狀態(對話框仍舊開着,按鈕失效了,光標狀態出現錯誤)。可是,使用這個技巧,你能夠將你的GUI程序恢復原始狀態並通知用戶出現了錯誤。對本身感受很棒吧,由於你寫了一個高質量的應用程序。

這個技巧並不僅適用於GUI程序。服務器端應用程序可使用這個技巧來釋放資源,防止虛擬機進入不穩定狀態。較早的捕獲錯誤並聰明的將其處理是好的程序員和普通程序員的區別之一。你已經明白了這些,我知道你想成爲哪一類程序員。

[color=cyan]關於做者

Josh Street是Bank of America的構架設計師。他主要負責電子商務平臺的開發。他的聯繫方式是rjstreet@computer.org。[/color]



附1


簡要的敘述error和exception



Error和Exception都繼承自Throwable,他們下列不一樣處:



Exceptions

1.能夠是 可被控制(checked) 或 不可控制的(unchecked)

2.表示一個由程序員致使的錯誤

3.應該在應用程序級被處理



Errors

1.老是 不可控制的(unchecked)

2.常常用來用於表示系統錯誤或低層資源的錯誤

3.如何可能的話,應該在系統級被捕捉程序員

相關文章
相關標籤/搜索