本文目錄一覽:
在寫java代碼的時候什麼時候才需要異常捕獲?
肯定是在你需要對異常進行處理的時候啊
舉個最常用的例子,線程的異常捕獲
基本上用線程大部分都會 進行異常捕獲
比如在線程睡眠的時候使用下面這條語句拋出異常
Thread.currentThread().interrupt();
這時候如果直接print的話,就會打印IllegalThreadStateException異常
這時候如果你不想 打印這個異常,想寫個別的,比如打印一個 HelloWord
在 catc語句塊中寫print(“HelloWord”)就行了
java中具體怎樣捕獲異常?
比如在dao層類中寫了一個可能會執行失敗的方法:\x0d\x0a捕獲異常的代碼如下: \x0d\x0apublic Map remove(int id) { \x0d\x0a Map map = new HashMap(); \x0d\x0a try { \x0d\x0a userGroupDao.remove(id); \x0d\x0a map.put(“isSuccess”, true); \x0d\x0a } catch (Exception e) { \x0d\x0a map.put(“isSuccess”, false); \x0d\x0a map.put(“errorMsg”, e.getMessage()); \x0d\x0a } \x0d\x0a return map; \x0d\x0a}
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(ab){
throw new ActionException(“a b”);
}
if(ab){
throw new ActionException(“a b”);
}
}
業務邏輯代碼中
public String process(){
try{
validate(a,b);
}catch(ActionException ae){
System.out.println(ae.getReturnMessage());
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/311403.html