概述
在这篇文章中,我们将探讨Scala中的异常处理。更确切地说,Scala中的try、catch 和finally关键字,我们将介绍它是如何工作的,它的用途是什么。
异常
让我们先了解一下什么是异常,因为这就是我们使用这些块的原因。简单的说,异常就是不需要的和意外的事件。这些事件会在程序的执行过程中发生,也就是在运行时发生。这些情况并不太危险,所以由程序本身来处理。
所有的异常和错误都是Throwable类的子类,Throwable类也是层次结构的基类,通过这个流程图可以更好地理解这一点。
Syntax : throw new ArithmeticException
try/catch结构
如果你对try和catch比较熟悉,那么Scala中的try catch结构与Java和其他语言不同。在Scala中,它是一个表达式,而不是为不同的情况反复编写catch块,try在这里给出一个值,可以与catch块中的情况相匹配。因此,我们不必为每一个可能的异常都写catch块。很棒,不是吗?
对于try/catch结构来说,这是一个完全陌生的概念,试想一下,有一段代码可能会抛出一个 "算术异常"。现在,这段代码可以用try 和 catch这两个关键字来处理,这种语法的写法被称为try/catch结构。
import java.io.IOException
// Creating an object
object ExceptionalObject
{
// Main method
def main(args:Array[String])
{
try
{
/*
Now this line will not throw a compilation error because it is syntactically okay
but not logically correct
*/
var N = 5/0
}
// after the exception is thrown by the try block it can be now handled in catch
catch
{
// Catch block contain cases and whatever case have the same exception that is thrown will get execute.
case i: IOException =>
{
println("IOException occurred.")
}
// In this case this case will run because 5/0 is an arithmetically wrong statement
case a : ArithmeticException =>
{
println("Arithmetic Exception occurred.")
}
}
}
}
最后我们来谈谈 "Final"!
Scala的finally块是用来执行需要执行的代码的,无论是否抛出了异常。这一点非常方便和有用。想知道怎么做吗?Finally可以在我们需要释放某些资源、关闭连接等情况下使用,基本上是在任何情况下都会执行的代码。
try {
//your scala code here
}
finally {
println("this block of code is always executed")
// your scala code here, such as to close a database connection
}
在上面的例子中,你可以看到我们没有添加catch块,因为并不总是需要添加catch块。上面的表达式在语法上是正确的,可以正常工作。
"try-catch-finally "子句
try-catch-finally将确保finally中的代码会被执行,即使异常被抛出或没有被抛出。让我们通过一个例子来看看。在下面的例子中,我们将抛出同样的异常("算术异常"),并使用finally来执行一些东西。
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
try
{
// creating an exception to throw
val = 5/0
}
catch
{
// Catch block contain cases.
case e: ArithmeticException => println(e) // exception will be matched and handled here
case ex: Exception => println(ex)
case th: Throwable=> println("unknown exception"+th)
}
finally
{
// Finally block will executeno matter what
println("this block always executes")
}
// rest program will execute
println(" rest of code executing")
}
}
最后块将被执行。
结语
在这篇文章中,我们已经看到了如何使用try/catch-construct和如何使用try-catch-finally。我们讨论了在哪些情况下我们可以使用从本文章中学到的东西。