Android 抛出异常并允许在方法中继续

Android 抛出异常并允许在方法中继续,android,exception,throw,Android,Exception,Throw,我在做一些验证。有一些必填字段,有些是可选字段。对于必填字段,我抛出异常,但对于可选字段,我必须打印警告,并在方法中进一步处理。我没有办法做警告部分。有人能帮忙吗 public void method(String param1, String param2){ if(param1 == null){ throw new IllegalArgumentException("mandatory field"); } //Here for param2, I want to throw

我在做一些验证。有一些必填字段,有些是可选字段。对于必填字段,我抛出异常,但对于可选字段,我必须打印警告,并在方法中进一步处理。我没有办法做警告部分。有人能帮忙吗

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

} 

throw是一个关键字,用于完成方法执行。如果抛出异常,则无法继续执行。您可以使用接口执行所需操作

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);
}
你可以用

    try{

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

尝试下面的代码,如果有任何问题,请告诉我

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

    }

这不是异常的工作方式。有几种方法可以解决这个问题:

  • 只是不要使用异常,而是打印错误(println()或一些文本字段、toast或其他内容)

  • 放置一个表示param2失败的布尔标记,并在方法末尾抛出异常

    m_param2 = true
    //...
    if (param2 == null) {
        m_param2 = false
    }
    // you proceed here
    if (!m_param2){
       // throw exception
    }
    
  • 对参数检查使用子方法,该方法在发生错误时总是抛出异常,并在主方法中捕获错误,然后决定执行什么操作
  • 对我来说,案例3没有多大意义,但这取决于您希望打印消息的方式和时间。如果在父层(运行方法的代码)中有什么东西在异常发生时自动生成错误消息,我将坚持我的第二个建议


    一般来说,我认为缺少可选参数不是真正的错误,因此不应该抛出异常。方法调用方需要以任何方式传递参数(当然,它可以为null)。

    try{…}catch(){…}finally{…}
    您所需要的只是try{}catch{}。看,似乎很相似。如果要继续,就不能抛出异常。只需使用代码中的某些函数将警告作为字符串发送到输出。