Java自訂Exception,javaexception

來源:互聯網
上載者:User

Java自訂Exception,javaexception

這裡總結一下Java的Exception,並實現一個自訂Exception類。 

總結: 

  1. Throwable對象分為兩種類型:Error(表示編譯時間和系統錯誤);Exception(在Java類庫、使用者方法以及運行時故障中拋出的異常)。
  2. Exception細分成兩種異常:受檢查異常(如,IOException, SQLException等。在編譯時間要被強制檢查的異常,需要用try, catch, finally關鍵字在編譯時間期處理,否則會報錯。);運行時異常(如,ArithmeticException, ClassCastException, IllegalArgumentException, IndexOutOfBoundsException, NullPointerException等。編譯器不會檢查這類異常。)
  3. Java編程中處理異常的最佳實務[4]:
    • 為可恢複的錯誤使用檢查型異常,為編程錯誤使用非檢查型錯誤。
    • 在finally程式塊中關閉或者釋放資源
    • 在堆疊追蹤中包含引起異常的原因
    • 始終提供關於異常的有意義的完整的信
    • 避免過度使用檢查型異常
    • 將檢查型異常轉為運行時異常
    • 記住對效能而言,異常代價高昂
    • 避免catch塊為空白
    • 使用標準異常
    • 記錄任何方法拋出的異常
  4. 受檢查異常和運行時異常的區別:
    • 受檢查異常需要自行處理,運行時異常不需要
    • 受檢查異常是Exception直接子類,運行時異常是RuntimeException的子類
    • 受檢查異常多是編程時出現的錯誤,運行時異常是程式運行時故障率較高
  5. 避免出現NullPointerException的最佳實務[5]:
    • 用已知的字串對象調用equals()和equalsIgnoreCase()方法【"hello".equals(objString)】;
    • 如果valueOf()和toString()方法的返回值一樣的話,用valueOf()方法代替toString()方法【當為null的對象調用toString()方法時會拋出NullPointerException異常而調用valueOf()方法時會返回一個"null"的封裝類】;
    • 使用對null安全的方法和庫【eg, StringUtils.isBlank(), isNumeric(), isWhiteSpace()等】;
    • 方法調用的返回值用返回空的集合或者空的數組避免返回null的情況【Collections.EMPTY_LIST, Collections.EMPTY_SET和Collections.EMPTY_MAP等】;
    • 使用@NotNull和@Nullable的註解明確指出是否可能有null的情況出現;
    • 避免代碼中出現不必要的自動裝箱和拆箱【避免類似的int a 出現接收返回值為null的情況,用Integer a代替更好】;
    • 遵守契約並且使用合理的預設值【通過定義什麼可以為空白,什麼不可為空,主叫方可以明確的作出判斷。】;
    • 在使用資料庫儲存物件時,要定義是否允許某個欄位為空白,這樣資料庫自身機制可以檢查是否為空白的情況,避免程式調用後出現非法的空欄位。
    • 使用null的封裝對象Null類。

自訂一個Exception類: 

ProjectNameException.java 內容如下: 

?

package com.trianlge23.projectname.exception;public class ProjectNameException extends Throwable {private static final long serialVersionUID = 8093803025939797139L;//exception codeprivate int exceptionCode;//exception detailed messageprivate String detailMsg;public ProjectNameException(int exceptionCode, String extraMsg) {super();this.setDetailMsg(exceptionCode);this.setExtraMsg(extraMsg);}public ProjectNameException(int exceptionCode) {super();this.setDetailMsg(exceptionCode);}//notice: we do not offer the set method to set the excption code.public int getExceptionCode() {return exceptionCode;}//if there has no extra message for this excption code, init it.private void setDetailMsg(int exceptionCode) {this.exceptionCode = exceptionCode;if (ProjectNameExceptionCode.EXCEPTION_CODE_MAP.containsKey(exceptionCode)) {this.detailMsg = ProjectNameExceptionCode.EXCEPTION_CODE_MAP.get(exceptionCode);} else {this.detailMsg = ProjectNameExceptionCode.EXCEPTION_CODE_MAP.get(ProjectNameExceptionCode.PROJECTNAME_EXCEPTION_CODE_NOT_FOUND);}}//if there has extra message for this exception code, add it.private void setExtraMsg(String extraMsg) {this.detailMsg += ProjectNameExceptionCode.EXTRA_EXCEPTION_MSG_SPLITER+ extraMsg;}//override the super class method getMessage()@Overridepublic String getMessage() {return this.detailMsg;}}


ProjectNameExceptionCode.java內容如下: 

?

package com.triangle23.projectname.exception;import java.util.HashMap;import java.util.Map;public class ProjectNameExceptionCode {//the separator between default message and extra message of exception.public static final String EXTRA_EXCEPTION_MSG_SPLITER = ": ";//the map stores the exception code and exception messagepublic static Map<Integer, String> EXCEPTION_CODE_MAP;public static final int PROJECTNAME_EXCEPTION_CODE_NOT_FOUND = 1;static {EXCEPTION_CODE_MAP = new HashMap<Integer, String>();EXCEPTION_CODE_MAP.put(PROJECTNAME_EXCEPTION_CODE_NOT_FOUND,"[PROJECTNAME Exception] Not found exception code.");}}



參考資料:

1. JDK1.7 API:http://docs.oracle.com/javase/7/docs/api/

2. Java編程思想(第四版)

3. Effective Java

4. Exception Handling Java Best Practices: 
http://javarevisited.blogspot.com/2013/03/0-exception-handling-best-practices-in-Java-Programming.html

5. Java Tips and Best practices to avoid NullPointerException: 
http://javarevisited.blogspot.com/2013/05/java-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html


說明:

如有錯誤還請各位指正,歡迎大家一起討論給出指導。

最後更新時間:2014-12-02


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.