Scala:插入异常及其管理



可能的重复项:
在 Scala 中抛出异常,什么是"官方规则"

如何处理可以从类启动的所有异常?我是Scala和Java的新手,我知之甚少,我从未使用过异常。

这是我的班级:

class Element (var name:String){
}//class Element

现在在我的类中放一个验证方法,如下所示:

class Element (var name:String){
  // VALIDAZIONE DI ELEMENT
  def validateElement : Boolean = {
    val validName : Boolean = try{if(this.name!=null) true 
    else throw new  IllegalArgumentException ("Element: ["+this+"] has no name.")
    }catch {
    case e: IllegalArgumentException => println("Exception : " + e); false
  }
  if (validName) true else false  
  }//def validate
}//class Element

该方法有效。但我有一个疑问。我把假的放在哪里?在捕获条款内?就像我一样?

非常感谢您的帮助。

有一次我有一个名为 NubLogger 的类来处理这样的问题。不要问名字的选择...

public static void handle(Throwable t) {
    if (t == null) {  
        t = new Throwable(NubLogger.class.getName() + ".handle((Throwable)null)");            
    }
    if (t instanceof RuntimeException) {
        log(t);
        throw (RuntimeException) t;
    } else if (t instanceof Exception) {
        log(t);
        throw new RuntimeException(t);
    } else if (t instanceof Error) {
        log(t);
        throw (Error) t;
    } else if (t instanceof Throwable) {
        log(t);
        throw new RuntimeException(t);
    } else {
        t = new UnsupportedOperationException("Unknown throwable type: " + t.getClass(), t); 
        log(t);
        throw (RuntimeException)t;
    }
}

编辑

class Element (var name:String){
    // VALIDAZIONE DI ELEMENT
    // Preferrable variant - use val name, not var name
    require(name != null)
    // VALIDAZIONE DI ELEMENT 2
    // Will work with var-s
    def validate = name != null
}//class Element

最新更新