# 异常
- Scala提供try和catch块来处理异常。try块用于包含可能出错的代码。catch块用于处理try块中发生的异常。可以根据需要在程序中有任意数量的try...catch块。
- 语法处理上和Java类似,但是又不尽相同
# 1. 捕获异常
/**
* 输出:
* 捕获了 ArithmeticException 异常
* 执行了 finally
*/
def main(args: Array[String]): Unit = {
try {
1/0
} catch {
case ex: ArithmeticException => println("捕获了 ArithmeticException 异常")
case ex: Exception => println("捕获了 Exception 异常")
} finally {
println("执行了 finally ")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 2. 手动抛出异常
- 用throw关键字,抛出一个异常对象。
- 所有异常都是Throwable的子类型。
- throw表达式是有类型的,就是Nothing。
- 因为Nothing是所有类型的子类型,所以throw表达式可以用在需要类型的地方
def test(): Nothing = {
throw new Exception("手动抛出了异常")
}
1
2
3
2
3
# 3. 声明异常
- Scala提供了throws关键字来声明异常。
- 可以使用方法定义声明异常。
- 它向调用者函数提供了此方法可能引发此异常的信息。
- 它有助于调用函数处理并将该代码包含在try-catch块中,以避免程序异常终止。
- 在scala中,可以使用throws注释来声明异常
def main(args: Array[String]): Unit = {
try{
test2()
} catch {
case ex: NumberFormatException => println("捕获到了 NumberFormatException ")
case ex: Exception => println("捕获了 Exception 异常")
} finally {
println("执行了 finally ")
}
}
@throws(classOf[NumberFormatException])
def test2(): Unit = {
"abc".toInt
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
← 面向对象