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");
}
}
这不是异常的工作方式。有几种方法可以解决这个问题:
m_param2 = true
//...
if (param2 == null) {
m_param2 = false
}
// you proceed here
if (!m_param2){
// throw exception
}
一般来说,我认为缺少可选参数不是真正的错误,因此不应该抛出异常。方法调用方需要以任何方式传递参数(当然,它可以为null)。
try{…}catch(){…}finally{…}
您所需要的只是try{}catch{}。看,似乎很相似。如果要继续,就不能抛出异常。只需使用代码中的某些函数将警告作为字符串发送到输出。