抛出异常并允许在方法中进一步进行

Throw exception and allow to proceed in method further

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

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");
        }

    }

这不是例外的工作方式。有几种解决方法:

  1. 只是不要使用异常并打印您的错误(println() 或一些文本字段、toast 或其他)

  2. 放置一个布尔标记,说明 param2 失败并在方法结束时抛出异常

    m_param2 = true
    //...
    if (param2 == null) {
        m_param2 = false
    }
    // you proceed here
    if (!m_param2){
       // throw exception
    }
    
  3. 使用子方法进行参数检查,它在发生错误时总是抛出异常,并在您的主方法中捕获错误,然后决定要做什么。

对我来说,情况 3 没有多大意义,但这取决于您想要打印消息的方式和时间。如果您在父层(运行您的方法的代码)中有一些东西在发生异常时自动生成错误消息,我会坚持我的第二个建议。

总的来说,我认为缺少可选参数不是真正的错误情况,因此不应抛出异常。方法调用者无论如何都需要传递参数(尽管它当然可以为 null)。