Catching Specific Errors
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 52 of 63.
A try block runs code that may throw. A catch handles a matching exception and lets execution continue after the try/catch. Catch a specific expected exception, such as NumberFormatException from toInt, so unrelated programming errors are not silently hidden.
Inside main:
try {
println("oops".toInt())
} catch (error: NumberFormatException) {
println("invalid")
}Parsing throws before println receives a number, so the matching catch prints the fallback message.
Catch the specific exception your operation is expected to throw.
Challenge
MediumComplete parseMessage with parameters text: String. Use try/catch around text.toInt(), without trimming. Return value=n on success, replacing n with the parsed integer, or invalid when NumberFormatException is thrown.
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type String. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun parseMessage(text: String): String {
// Write your solution here.
return ""
}
fun main() {
val text = readLine().orEmpty()
println(parseMessage(text))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals5Project - Contact Book
Save ContactsFind Contacts8Sorting and Grouping
Sorting by a KeyCombining ComparisonsGrouping ValuesAssociating by a KeyRecap - Length Leaderboard11Error Handling
Parsing Without ExceptionsCatching Specific ErrorsTry as an ExpressionValidating with RequireRecap - Validated QuantitiesPractice on your own: Kotlin playground