当前位置:网站首页>Android kotlin exception handling
Android kotlin exception handling
2022-06-23 17:47:00 【Susceptible to cold】
Throws Exception
Kotlin Exceptions and Java The same as , try…catch…finally Code block handling exception , The only difference is :Kotlin All the exceptions are Unchecked exceptions.
checked exceptions Is an exception that must be defined and handled on a method , such as Java Of IoException.
Kotlin Throw an exception using Throws Annotation to achieve , as follows :
@Throws(IOException::class)
fun createDirectory(file: File) {
if (file.exists())
throw IOException("Directory already exists")
file.createNewFile()
}When we're in java When used in code , as follows :
Will remind us to report errors , But if kotlin When used in the document , There will be no hint .
Custom exception
/** * @author : zhaoyanjun * @time : 2021/7/5 * @desc : Custom exception */ class CommonException(code: Int, message: String) : Exception(message)
Use :
@Throws(CommonException::class)
fun createDirectory(file: File) {
if (file.exists())
throw CommonException(0, "file is exists")
file.createNewFile()
}runCatching
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
kotlin.runCatching {
sum(2, 4)
}.onSuccess {
Log.d("yy--", " Normal results $it")
}.onFailure {
it.printStackTrace()
Log.d("yy--", " The result is abnormal ${it.message}")
}
}
fun sum(num1: Int, num2: Int): Int {
1 / 0
return num1 + num2
}
}getOrDefault
val result = kotlin.runCatching {
sum(2, 4)
}.onSuccess {
Log.d("yy--", " Normal results $it")
}.onFailure {
it.printStackTrace()
Log.d("yy--", " The result is abnormal ${it.message}")
}.getOrDefault(100)
// If it works properly , Just go back to 6, Return if the operation is abnormal 100
Log.d("yy--", " result $result")isSuccess、isFailure
val result = kotlin.runCatching {
sum(2, 4)
}.onSuccess {
Log.d("yy--", " Normal results $it")
}.onFailure {
it.printStackTrace()
Log.d("yy--", " The result is abnormal ${it.message}")
}.isFailureexceptionOrNull
public fun exceptionOrNull(): Throwable? =
when (value) {
is Failure -> value.exception
else -> null
}If there is an exception, it returns an exception , Otherwise return to Null
getOrNull
@InlineOnly
public inline fun getOrNull(): T? =
when {
isFailure -> null
else -> value as T
}If it fails , Just go back to null , Otherwise return to
边栏推荐
- How about stock online account opening and account opening process? Is online account opening safe?
- Cross browser common events
- 《AN4190应用笔记 天线选择指南》——天线理论2
- Thymeleaf - learning notes
- FPN characteristic pyramid network
- MySQL transaction submission process
- Postgresql_根据执行计划优化SQL
- High availability solution practice of mongodb advanced applications (4)
- The official Chinese course of zero foundation introduction jetpack compose is coming
- Postgresql_ Optimize SQL based on execution plan
猜你喜欢

内网渗透令牌窃取
![[30. concatenate substrings of all words]](/img/e7/453c8524a23fbb7501e85140547ce1.png)
[30. concatenate substrings of all words]

Why do we say that the data service API is the standard configuration of the data midrange?

Database Experiment 2 query

Huawei mobile phones install APK through ADB and prompt "the signature is inconsistent. The application may have been modified."

10分钟后性能测试瓶颈调优!想进大厂这个必须会

QT布局管理器【QVBoxLayout,QHBoxLayout,QGridLayout】

美团三面:聊聊你理解的Redis主从复制原理?
![[mae]masked autoencoders mask self encoder](/img/08/5ab2b0d5b81c723919046699bb6f6d.png)
[mae]masked autoencoders mask self encoder

《MPLS和VP体系结构》
随机推荐
mysql-选择使用Repeatable read的原因
解析 | 模-数(A/D)转换器
How to design a seckill system?
Answer 01: why can Smith circle "allow left string and right parallel"?
Ctfshow PHP features
Tencent three sides: how to duplicate 4billion QQ numbers?
How to make sales management more efficient?
AMQP protocol
Goframe framework: fast implementation of service end flow limiting Middleware
Cross browser common events
Importance of ERP management system
Petitpotam – NTLM relay to ad CS
C. Phoenix and Towers-Codeforces Global Round 14
QT当中的【QSetting和.ini配置文件】以及【创建Resources.qrc】
一文入门智能开关的3种功能形态
What is the problem with TS File Error 404 when easynvr plays HLS protocol?
Why do we say that the data service API is the standard configuration of the data midrange?
Asemi ultrafast recovery diode es1j parameters, es1j package, es1j specification
FPN characteristic pyramid network
[network communication -- webrtc] source code analysis of webrtc -- bandwidth estimation at the receiving end