struts異常處理機制

2021-05-27 23:49:58 字數 2250 閱讀 2168

異常處理,通常有兩種方式,程式設計式異常和自動異常處理。

程式設計式異常

即在action

中呼叫業務邏輯時通過

try/catch

來截獲異常之後,手動對異常進行處理。

自動異常處理機制

即在action

中不捕捉異常,而是交給

struts

框架來處理。 在

struts1.x

的版本中加入了對異常的處理

exceptionhandler

,有了它就不需要用

try/catch

等捕獲異常,一旦出現我們已經定義的異常,那麼就會轉到相應的頁面,並且攜帶定製的資訊。

struts

框架提供了預設的異常處理

org.apache.struts.action.exceptionhandler,

他的execute()

方法負責處理異常。在需要實現自定義處理時重寫方法,可以在配置檔案定義由誰來處理

action

類中擲出的某種異常。

struts

框架處理異常的流程

struts

捕獲異常,在異常處理**中,建立描述資訊的

actionmessage

物件把它儲存在

actionmessages

中,然後把

actionmessages

儲存在特定範圍(配置檔案中的

scope

),然後可以用

檢索特定範圍內的

actionmessges

物件。

struts自動異常處理的**示例:

**:

/** * 使用者管理類

* @author administrator

* */

public class usermanager

if (!"admin".equals(password))

}}

/**

* errorcode異常處理類

* @author administrator

* */

public class errorcodeexception extends runtimeexception

public errorcodeexception(string errorcode,object args)); }

public errorcodeexception(string errorcode,object args)

public string geterrorcode()

public object getargs()

}

/**

* errorcodeexception異常處理處理類

* @author administrator

* */

public class errorcodeexceptionhandler extends exceptionhandler

actionforward forward = null;

actionmessage error = null;

string property = null;

if (ae.getpath() != null) else

if (ex instanceof moduleexception) else

this.logexception(ex);

// store the exception

request.setattribute(globals.exception_key, ex);

this.storeexception(request, property, error, forward, ae.getscope());

return forward;

}}

public class loginaction extends dispatchaction

}

配置檔案:

type="com.tgb.struts.loginaction"

name="loginform"

scope="request"

input="/login.jsp"

>

介面:

異常處理機制

異常處理的三個步驟 檢查異常,丟擲異常,處理異常 異常處理基本原理 把需要檢測的程式放到try塊中,把異常處理的程式放在catch塊中。如果執行乙個函式出現了異常,可以丟擲異常資訊。然後查詢try塊下面的catch塊是否可以處理該異常。如果該函式不處理該異常,將傳遞給它的上一級函式 呼叫函式 如果它...

異常處理機制

1 c 中異常處理機制使得異常的引發和異常的處理不必在同乙個函式中。2 異常是專門針對抽象程式設計中的一系列錯誤處理的,c 的函式機制是棧結構,先進後出,依次訪問,無法跳躍。3 異常超脫於函式機制,決定了其對函式的跨越式回跳。4 異常跨越函式 普通用法 基本用法 void add int a,int...

異常處理機制

異常處理機制分為以下2點 異常處理五個關鍵字 try catch finally throw throws 用了try catch程式出現異常不會終止,會丟擲異常繼續執行下面任務 public static void main string args catch error e catch exce...