Scala异常的工作机制和Java或C++一样
throw new IllegalArgumentException("x should not be negative")
控制权将在离抛出点最近的处理器恢复,如果没有符号要求的异常处理器,则程序退出。
与Java不同的是,Scala没有checked异常。
throw表达式有特殊的类型Nothing,在if/else表达式很有用。
if(x>=0){sqrt(x)
}else throw new IllegalArgumentException("x should not be negative")
捕获异常采用的是模式匹配方法
try{
process(new URL("http://horstmann.com/fred-tiny.gif"))
}catch{
case _: MalformedURLException=>println("Bad URL:"+url)
case ex: IOException=>ex.printStackTrace()
}
与Java、C++一样,更通用的异常排在更具体的异常之后。
try/finllay可以释放资源
var in=new URL("http://horstmann.com/fred.gif").openStream()
try{
process(in)
}finally{
in.close()
}