0

Possible Duplicate:
Throwing exceptions in Scala, what is the “official rule”

How do I handle all exceptions that I can launch from a class? I'm new to Scala and Java I know little, I've never used exceptions.

This is my class:

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

Now put a validate method in my class, like this:

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

The method works. But I have a single doubt. Where do I put the false of else? Inside the catch clause? As I did?

Thank you very much for your help.

Community
  • 1
  • 1
user1826663
  • 357
  • 1
  • 3
  • 15
  • 3
    Please do at least some research prior to asking. If you are totally new to exceptions, [a basic Google search](https://www.google.com/search?q=scala+exceptions) offers you a bunch of decent looking tutorials. Moreover, check the existing related questions (shown on the right) before asking a similar one. – Péter Török Dec 10 '12 at 08:49
  • Catching the exception immediately doesn't make sense. If you want to throw an exception to the caller in case validation fails, just throw it and let it propagate upwards to the caller, i.e. do not catch it inside `validateElement`. If you want to return false in case validation fails, just return false and don't bother with exceptions. Again I would recommend reading a decent tutorial on exceptions. – Péter Török Dec 12 '12 at 10:42

1 Answers1

0

Once I had a class named NubLogger for handling such an issues. Don't ask about the choice of name...

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

EDIT

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
idonnie
  • 1,703
  • 12
  • 11