Scala try-catch語句


Scala提供trycatch塊來處理異常。try塊用於包含可疑程式碼。catch塊用於處理try塊中發生的異常。可以根據需要在程式中有任意數量的try...catch塊。

Scala try catch範例1

在下面的程式中,我們將可疑程式碼封裝在try塊中。 在try塊之後使用了一個catch處理程式來捕獲異常。如果發生任何異常,catch處理程式將處理它,程式將不會異常終止。

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 Demo{  
    def main(args:Array[String]){  
        var e = new ExceptionExample()  
        e.divide(100,0)  

    }  
}

將上面程式碼儲存到原始檔:Demo.scala中,使用以下命令編譯並執行程式碼 -

D:\software\scala-2.12.3\bin>scalac Demo.scala
D:\software\scala-2.12.3\bin>scala Demo.scal
java.lang.ArithmeticException: / by zero
Rest of the code is executing...

Scala Try Catch範例2

在這個例子中,catch處理程式有兩種情況。 第一種情況將只處理算術型別異常。 第二種情況有Throwable類,它是異常層次結構中的超類。第二種情況可以處理任何型別的異常在程式程式碼中。有時當不知道異常的型別時,可以使用超類 - 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 Demo{  
    def main(args:Array[String]){  
        var e = new ExceptionExample()  
        e.divide(100,10)  

    }  
}

將上面程式碼儲存到原始檔:Demo.scala中,使用以下命令編譯並執行程式碼 -

D:\software\scala-2.12.3\bin>scalac Demo.scala
D:\software\scala-2.12.3\bin>scala Demo.scal
found a unknown exceptionjava.lang.ArrayIndexOutOfBoundsException: 10
Rest of the code is executing...