Scala 使用“try … catch … finally”来处理异常
try块:用于包含可能出错的代码
catch处理程序:用于处理 try 块中发生的异常
finally块:不管有没有捕获异常,最终都会执行的代码
Java(回顾)
public class ExceptionOperation {public static void main(String[] args) {try {int i = 1 / 0;System.out.println(i);} catch(ArithmeticException e) { // (1)e.printStackTrace();} catch(Exception e) { // (2)System.out.println("捕获到异常");} finally {System.out.println("finally!!!");}}}
✍ 思考题
问:当调换代码中(1)和(2)的位置,执行代码后的结果会是什么?密码:123
📝 说明
- 按照 “try-catch-catch…-finally”的方式处理异常
- 不管有没有异常捕获,finally 代码块最终都会执行;一般用于释放资源
可以有多个 catch 块,范围小的异常类写在前面,范围大的写在后面,否则编译错误
Scala
捕获异常
object ExceptionOperation {def main(args: Array[String]): Unit = {catchException()}def catchException(): Unit = {try {val res = 1 / 0} catch {case ex: ArithmeticException => println("捕获了除数为0的算数异常") // (1)case ex: Exception => println("捕获了异常") // (2)} finally {println("finally!!!")}}}
✍ 思考题
问:当调换代码中(1)和(2)的位置,执行代码后的结果会是什么?密码:123
📝 说明
- Scala 的异常工作机制和 Java 一样,但是 Scala 没有“checked(编译时)”异常,异常都是在运行时捕获的
- 在 Scala 的 catch 处理程序中,借用了模式匹配的思想来对异常进行匹配
- Scala 的异常捕获机制是按 catch 子句的次序捕捉的,所以具体的异常要放在前面,普遍的放在后面
catch 子句中范围广的异常放在范围小的前面不会像 Java 一样报错,但是这种编程风格不好,不要这么做
抛出异常
object ExceptionOperation {def main(args: Array[String]): Unit = {throwException1()throwException2()}// 方式一def throwException1(): Nothing = {throw new ArithmeticException("算数异常~")}// 方式二// classOf[NumberFormatException] 等同于 Java 中的 NumberFormatException.class@throws(classOf[NumberFormatException])def throwException2()= {"abc".toInt}}
📝 说明
Scala 可以使用两种方式抛出异常:通过 throw 关键字抛出异常或者使用 throws 注解声明异常
- 所有异常都是 Throwable 的子类型;throw 表达式是有类型的,它的类型是 Nothing
