💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**1. 捕获异常** ```scala try{}catch{ case ex:Exception => {}}finally{} ``` ```scala def main(args: Array[String]): Unit = { try { val y = 100 val x = y / 0 println(y) } catch { case ex:ArithmeticException => { ex.printStackTrace() // java.lang.ArithmeticException: / by zero } case ex:IOException => { ex.printStackTrace() } case ex:Exception => { ex.printStackTrace() } } finally { println("Exiting finally...") // Exiting finally... } } ``` <br/> **2. 抛出异常** ```scala throw new Exception ``` ```scala def main(args: Array[String]): Unit = { val x = 3 if (x > 2) throw new Exception("3大于2") // Exception in thread "main" java.lang.Exception: 3大于2 } ``` <br/> **3. Either[A, B]处理异常** * Either[A, B] 表示要么包含一个类型为A的实例,要么包括一个类型为B的实例; * Either只有两个子类型:Left、Right,如果Either[A, B]对象包含的是A的实例,则它是Left实例,否则是Right实例; * Either用于异常处理时,一般约定:Left 代表出错的情况,Right 代表成功的情况; ```scala object App{ def main(args: Array[String]): Unit = { def divide(x:Int):Either[String, Int] = { if (x == 0) Left("除数不能为0") else Right(100/x) } def matchTest(x:Int)=divide(x) match { case Left(errMsg) => println(errMsg) case Right(result) => println(result) } matchTest(0) // 除数不能为0 matchTest(2) // 50 } } ``` <br/> **4. allCatch处理异常** ```scala object App{ def main(args: Array[String]): Unit = { scala.util.control.Exception.allCatch.opt("42".toInt) // Some(42) scala.util.control.Exception.allCatch.opt("42a".toInt) // None scala.util.control.Exception.allCatch.toTry("42".toInt) // 42 scala.util.control.Exception.allCatch.toTry("42a".toInt) // Failure (e) scala.util.control.Exception.allCatch.withTry("42".toInt) // Success(42) scala.util.control.Exception.allCatch.withTry("42a".toInt) // Failure (e) scala.util.control.Exception.allCatch.either("42".toInt) // Right(42) scala.util.control.Exception.allCatch.either("42a".toInt) // Left(e) } } ``` <br/> **5. failAsValue处理异常** 当发生异常时,会提供一个默认值。 ```scala object App{ def main(args: Array[String]): Unit = { val result = scala.util.control.Exception.failAsValue(classOf[Exception])(-9999)("42a".toInt) println(result) // -9999 } } ```