2017-03-07 50 views
0

我正在進行一些驗證。有一些必填字段,其中一些是可選的。對於必填字段,我拋出異常,但對於可選字段,我必須打印警告,並且必須在我的方法中繼續。我沒有辦法做警告部分。有人可以幫忙嗎?拋出異常並允許繼續進行方法

public void method(String param1, String param2){ 
if(param1 == null){ 
    throw new IllegalArgumentException("mandatory field"); 
} 
//Here for param2, I want to throw eception, but want to proceed further to next line. 

//Execute my code here 

} 
+2

'try {...} catch(){...} fincally {...}' –

+0

您只需要嘗試{} catch {}。看到[這](http://stackoverflow.com/questions/9329568/how-to-continue-executing-a-java-program-after-an-exception-is- thrown),似乎很相似。 – gvlachakis

+1

如果你想繼續,你不能拋出異常。只需發送警告以字符串的形式輸出,在代碼中使用一些函數即可。 – Jadamec

回答

0

這不是異常情況。有幾種方法來解決這個問題:

  1. 只要不使用異常和打印錯誤,而不是(的println()或某些文本框,烤麪包或其他)

  2. 放置一個boolean值標記說,參數2失敗,在方法

    m_param2 = true 
    //... 
    if (param2 == null) { 
        m_param2 = false 
    } 
    // you proceed here 
    if (!m_param2){ 
        // throw exception 
    } 
    
  3. 使用子方法的參數檢查錯誤發生時總是拋出一個異常,並趕在你的主法的錯誤,並決定做什麼,然後結束扔你例外。

對於我來說,情況3沒有多大意義,但這取決於您打算如何以及何時打印該消息。如果你在父層(運行你的方法的代碼)中有東西在發生異常時自動生成錯誤消息,我會堅持我的第二個建議。

在一般情況下,我認爲缺少可選參數是沒有真正的錯誤的情況下,所以不應該拋出異常。無論如何,方法調用者都需要傳遞該參數(儘管它當然可以爲null)。

0

罰球是一個關鍵字,它完成的方法執行,你不能拋出一個異常繼續,你可以使用一個接口,做你想做

public void method(String param1, String param2,Listener listener){ 
    if(param1 == null){ 
     listener.IllegalArgumentException("mandatory field"); 
     return; 
    } 
    listener.IllegalArgumentException("mandatory field"); 

     //Execute my code here 

} 
interface Listener{ 
    void IllegalArgumentException(String string); 
} 
0

你可以使用

try{ 

    } catch (Exception e){ 
     // you can ignore if you want to 
    }finally { 
     //rest of your code here 
    } 
0

嘗試下面的代碼讓我知道是否有任何問題。

public void method(String param1, String param2){ 
     if(param1 == null){ 
      throw new IllegalArgumentException("mandatory field"); 
     } 
     if(param2 == null) { 
      Log.d("Error", "param2 is null"); 
     } 

    }