scala - How to handle different cases of Failure from Try -


i want handle different cases of failure (returned try).

example code

main(args(0)) match {   case success(result) => result.foreach(println)   case failure(ex) => ex match {     case filenotfoundexception =>       system.err.println(ex.getmessage)     case statsexception =>       system.err.println(ex.getmessage)     case _ => {       ex.printstacktrace()     }       system.exit(1)   } } 

if statsexception or filenotfoundexception print message, other exceptions print stack trace.

however ex ever throwable, , case statsexception fruitless type test (a value of type throwable cannot statsexception.type according intellij)

worse compile errors: java.io.filenotfoundexception not value

what's best way handle different cases of failure in idiomatic way?

i simplify own answer:

main(args(0)) map (_ foreach println) recover {   case ex@(_: filenotfoundexception | _: statsexception) =>     system.err.println(ex.getmessage)     system.exit(1)   case ex =>     ex.printstacktrace()     system.exit(1) } 

in first case clause matching 2 alternative. scala forbids declarations case ex: filenotfoundexception | ex: statsexception, assign whole match result via @ symbol. see this question more details


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -