① java中具體怎樣捕獲異常
try{//可能會發生異常的句子}catch{//處理異常的代碼,讓程序在異常之後執行該代碼}finally{必須執行的代碼{
② java如何自定義一個可捕獲的異常
1)先定義一個類繼承Exception(或者別的RuntimeException等);
2)然後寫個方法可能拋出這個異常,並且什麼情況下會拋出異常;
3)調用這個方法,寫try,catch語句,捕獲這個異常;
小例子,你參考看下:
{
publicUserNotFoundException(){}
publicUserNotFoundException(Stringmessage){
super(message);
}
publicvoidf()throwsUserNotFoundException{
thrownewUserNotFoundException("用戶名不對");
}
}
publicclassException{
publicstaticvoidmain(Stringargs[]){
try{
newUserNotFoundException().f();
}catch(UserNotFoundExceptione){
System.out.println(e.getMessage());
}
}
}
③ java 如何捕獲資料庫底層異常
Throwable ct=e,lt=e; for(;;){ct=ct.getCause();if(ct==null)break;lt=ct;} 底層不要處理異常直接拋 ; 或者捕捉e throw e ; 或者用e.cause構造異常。
④ java異常的捕獲
首先自定義一個異常類
public class ActionException extends Exception{
public String returnMessage;
public ActionException(String returnMessage){
this.returnMessage = returnMessage;
}
public String getReturnMessage(){
return this.returnMessage;
}
代碼中如果用到這個自定義的異常類,這里的代碼只是做了個演示
private void validate(int a,int b)throws ActionException{
if(a>b){
throw new ActionException("a > b");
}
if(a<b){
throw new ActionException("a < b");
}
}
業務邏輯代碼中
public String process(){
try{
validate(a,b);
}catch(ActionException ae){
System.out.println(ae.getReturnMessage());
}
}