Summary - Exceptions
- Kotlin course
- Beginner
- Lesson 105/116
- 5 min
Combine try/catch, finally and try expression to write a bank account class.
Summary - Exceptions
In this group you learned to catch errors with try/catch, raise with throw, clean up with finally, use try as an expression and define custom exception classes.
Now it is time to combine them in a small task: define a custom error class, throw it, catch it and finally do cleanup. This is a small sample of a real error-handling flow.
Practice Build a full flow with a custom error
Define the class MyError(message: String) : Exception(message). Write fun load() that throws MyError("Loading failed"). In main set up try/catch/finally; on error print e.message, and in finally call println("Done").
Starter code
fun main() {
// Define an error class, throw in a function, wrap with try-catch-finally
}Sample solution
class MyError(message: String) : Exception(message)
fun load() {
throw MyError("Loading failed")
}
fun main() {
try {
load()
} catch (e: MyError) {
println(e.message)
} finally {
println("Done")
}
}Expected output
Yükleme başarısız Bitti
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is true?
- finally always runs Correct answer
- throw catches errors
- catch raises errors
- try catches errors
Explanation: finally runs whether or not there is an error.
2 Match tool to purpose
| Term | Meaning |
|---|---|
try |
Trial |
catch |
Catching |
finally |
Cleanup |
throw |
Raising |
3 Fill in the blank: write catch
try {
load()
} ____ (e: MyError) {
println(e.message)
}
try {
load()
} catch (e: MyError) {
println(e.message)
}
Explanation: catch catches the MyError.