Kotlin 中的异常处理与示例
异常是运行时出现的错误,会破坏程序的执行流程。基本上例外是在运行时发生的不需要的事件。我们可以处理这种错误的方法称为异常处理。
异常类型
- Checked Exception:在编译时发生的异常,或者我们可以说在编译时进行检查的异常称为Checked Exception。示例 - IOException ,一些文件相关的 Exception等
- 未经检查的异常:在运行时发生的异常称为未经检查的异常。示例 - OutofBound异常。
Note: In Kotlin we have only unchecked Exceptions which only figure out at the runtime.
如何处理异常?
我们有一些关键字可以帮助我们处理异常。
- Try // This will try to find the exception
- Throw // If exception found then it will throw the exception
- Catch // After throwing it will catch the exception and execute their body.
我们还有一个名为finally的关键字,它总是会执行我们是否有异常。在此,我们有一些始终需要执行的重要代码。
Note: If the program exit by exitProcess(Int) or abort(), then the finally will not be executed.
如何使用try-catch和 finally?
try
{
// your code which
// may throw an exception
}
catch(ex : ExceptionName)
{
// Exception handle code
}
finally
{
// this will execute every time
// either we found exception or not
}
示例 1:除以零
Kotlin
fun main()
{
try
{
// calling the function
divide(10, 0)
}
catch (ex : Exception)
{
// or you can also write your
// own handle here
println(ex.message)
}
}
// function which may give exception
fun divide(a : Int, b : Int)
{
if (b == 0)
throw Exception("Divide by zero")
// even if you didn't write
// this throw it will work fine.
println("Division is :" + a / b)
}
Kotlin
fun main()
{
// first try block
try
{
// didn't throw any exception
divide(20, 10)
}
catch (ex : Exception)
{
// or you can also write your
// own handle here
println(ex.message)
}
finally
{
println("I'm executed")
}
// 2nd try block
try
{
// throw an exception
divide(10, 0)
}
catch (ex : Exception)
{
// or you can also write your
// own handle here
println(ex.message)
}
finally
{
println("I'm executed")
}
}
fun divide(a : Int, b : Int)
{
if (b == 0)
throw Exception("Divide by zero")
println("Division is :" + a / b)
}
输出:
Divide by zero
示例 2:让我们使用 try-catch 和 finally 尝试相同的代码。
科特林
fun main()
{
// first try block
try
{
// didn't throw any exception
divide(20, 10)
}
catch (ex : Exception)
{
// or you can also write your
// own handle here
println(ex.message)
}
finally
{
println("I'm executed")
}
// 2nd try block
try
{
// throw an exception
divide(10, 0)
}
catch (ex : Exception)
{
// or you can also write your
// own handle here
println(ex.message)
}
finally
{
println("I'm executed")
}
}
fun divide(a : Int, b : Int)
{
if (b == 0)
throw Exception("Divide by zero")
println("Division is :" + a / b)
}
输出:
Division is : 2
I'm executed
Divide by zero
I'm executed
请注意,在上面的示例中,finally 在两种情况下都会执行,无论是否发生异常。