Skip to Content
Head First Kotlin程序设计
book

Head First Kotlin程序设计

by Dawn Griffiths, David Griffiths
August 2020
Intermediate to advanced
483 pages
11h 24m
Chinese
China Machine Press
Content preview from Head First Kotlin程序设计
240
8
使用
t r y/c a t c h
捕获异常
通过将有风险的代码包在tr y/catc h 块中可以捕获异常。
tr y/
catch
块告诉编译器在你要执行的代码中可能会有异常发生,而你准
备处理它。编译器并不关心处理的方式,它只关注声明处理异常这件
事。
这是
try/c atc h
块的样子:
fun myFunction(str: String) {
try {
val x = str.toInt()
println(x)
} catch (e: NumberFormatException) {
println("Bummer")
}
println("myFunction has ended")
}
try/c atc h
块的try部分包含可能引起异常的危险代码。在上面的例
子中是这部分:
try {
val x = str.toInt()
println(x)
}
它的catch部分指定了想要捕获的异常以及想要在捕获后执行的代
码。所以如果我们的危险代码抛出一个
NumberFormatException
我们将像这样捕获它并打印出一条重要的信息:
我要
TRY
一下这项
高风险的运动,如
果失败的话,我也会
CATCH
住自己。
catch (e: NumberFormatException) {
println("Bummer")
}
然后执行
catch
块后面的所有代码,例子中的代码是:
println("myFunction has ended")
这是
try
这是
catch
只有在异常被捕获时才会执行这行
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

面向对象的思考过程(原书第5版)

面向对象的思考过程(原书第5版)

马特 魏斯费尔德
GraphQL 学习指南

GraphQL 学习指南

Eve Porcello, Alex Banks
前端架构设计

前端架构设计

Micah Godbolt

Publisher Resources

ISBN: 9787111662358