- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 303字
- 2021-06-24 14:13:28
Exception handling
Handling of exceptions is almost identical to the way Java handles exceptions with one key difference-in Kotlin all exceptions are unchecked.
As a reminder, checked exceptions are those that must be declared as part of the method signature or handled inside the method. A typical example would be IOException, which is thrown by many File functions, and so ends up being declared in many places throughout the IO libraries.
Unchecked exceptions are those that do not need to be added to method signatures. A common example would be the all too familiar NullPointerException, which can be thrown anywhere. If this was a checked exception, literally every function would need to declare it!
In Kotlin, since all exceptions are unchecked, they never form part of function signatures.
The handling of an exception is identical to Java, with the use of try, catch, and finally blocks. Code that you wish to handle safely can be wrapped in a try block. Zero or more catch blocks can be added to handle different exceptions, and a finally block is always executed regardless of whether an exception was generated or not. The finally block is optional, but at least one catch or finally block must be present.
In this example, the read() function can throw an IOException exception, and so we may wish to handle this potential exception in our code. In this case, we assume the input stream must always be closed, regardless of whether the reading is successful or not, and so we wrap the close() function in a finally block:
fun readFile(path: Path): Unit { val input = Files.newInputStream(path) try { var byte = input.read() while (byte != -1) { println(byte) byte = input.read() } } catch (e: IOException) { println("Error reading from file. Error was ${e.message}") } finally { input.close() } }
- Bootstrap Site Blueprints Volume II
- Python機(jī)器學(xué)習(xí):數(shù)據(jù)分析與評(píng)分卡建模(微課版)
- React Native Cookbook
- 深入淺出Android Jetpack
- Mastering Yii
- Windows Server 2012 Unified Remote Access Planning and Deployment
- Spring實(shí)戰(zhàn)(第5版)
- Web程序設(shè)計(jì)(第二版)
- Java項(xiàng)目實(shí)戰(zhàn)精編
- Modern JavaScript Applications
- Java系統(tǒng)化項(xiàng)目開發(fā)教程
- Java Fundamentals
- Microsoft 365 Certified Fundamentals MS-900 Exam Guide
- Moodle 3 Administration(Third Edition)
- C++程序設(shè)計(jì)教程