Scala Try Catch
Scala Try Catch
Scala 提供了 try 和 catch 块来处理异常。 try 块用于包含可疑代码。 catch 块用于处理 try 块中发生的异常。您可以根据需要在程序中包含任意数量的 try catch 块。
Scala Try Catch 示例
在下面的程序中,我们附上了我们的可疑代码在 try 块内。在 try 块之后,我们使用了一个 catch 处理程序来捕获异常。如果发生任何异常,catch handler会处理它,程序不会异常终止。
class ExceptionExample{
def divide(a:Int, b:Int) = {
try{
a/b
}catch{
case e: ArithmeticException => println(e)
}
println("rest of the code is executing...")
}
}
object MainObject{
def main(args:Array[String]){
var e = new ExceptionExample()
e.divide(100,0)
}
}
输出:
java.lang.ArithmeticException: / by zero
rest of the code is executing...
Scala Try Catch Example 2
在这个例子中,我们的 catch 处理程序中有两种情况。第一种情况将仅处理算术类型异常。第二种情况有 Throwable 类,它是异常层次结构中的超类。第二种情况能够处理程序中的任何类型的异常。有时当你不知道异常的类型时,你可以使用超类。
class ExceptionExample{
def divide(a:Int, b:Int) = {
try{
a/b
var arr = Array(1,2)
arr(10)
}catch{
case e: ArithmeticException => println(e)
case ex: Throwable =>println("found a unknown exception"+ ex)
}
println("rest of the code is executing...")
}
}
object MainObject{
def main(args:Array[String]){
var e = new ExceptionExample()
e.divide(100,10)
}
}
输出:
found a unknown exceptionjava.lang.ArrayIndexOutOfBoundsException: 10
rest of the code is executing...