java异常分类:
主类:Throwable
子类:error(内部错误/资源耗尽,基本不能处理)
子类:Execption(运行时异常、检查异常)
运行异常:RuntimeException
1.空指针 NullPointerException
2.参数不匹配 ClassCastException
3.数组越界 …
检查异常:CheckedException
1.IO读文件异常 IOException
2.SQLException …
如何处理:
throw(方法内)/throws(方法名后) 不处理,抛出
try{…}catch{…}[finally{…}] 抓取并处理异常
scala 异常处理
处理方法1:
throw new ExceptionType 抛出异常,暂不处理
try(…)catch( case …) try-catch处理(基本与java类似)
处理方法2:
使用Either处理异常(Either用于异常处理时,一般约定:Left 代表出错的情况,Right 代表成功的情况)
def divide(x:Int): Either[String,Int] ={
if(x==0)
Left("除数不能为0")
else
Right(100/x)`
}
def test(x:Int)=divide(x) match {
case Left(errMsg)=>println(errMsg)
case Right(result)=>println(result)
}
test(0)
test(1)