People interact with software as developers and as users, and sometimes they make mistakes. A user could, for example, input invalid data, and a developer could forget to validate it. It’s important to notice and handle defects and potential weaknesses in your code in order to avoid unpredictable behavior of your app and unsatisfying experiences for its users.
Exceptions are a convenient way to detect errors in software. This concept is used in a wide variety of programming languages, including Kotlin.
What is an exception?
An exception is primarily an event which signals that something went wrong during program execution. Exceptions are represented by the Exception Java class, which is a superclass of all exceptions in Java and Kotlin programs — e.g., NullPointerException, IOException, etc. Depending on their nature, these events should be caught at runtime or fixed to prevent the exception from happening in the first place. I will discuss catching exceptions later in this chapter
Conversely, another type of critical event, an error — represented by Error and its subclasses — should not be handled but should instead be fixed, because it’s the result of serious problems in a program, like inappropriate memory usage, for example.
Both Exception and Error extend Throwable and, therefore, could be thrown by the JVM or manually from code using the keyword throw, in order to notify the user of the code that a problem occurred. Every Throwable object can contain a message and a cause — another Throwable instance that caused this error or exception, and a stacktrace.
Let’s see how a program behaves when an exception occurs and you don’t handle it. Imagine a main() function that calls someFunction(), which calls anotherFunction(), which in turn calls oneMoreFunction() that throws an exception with the message “Some exception”.
Your program can be represented as a long chain of function invocations. When something goes wrong somewhere in oneMoreFunction(), an exception gets thrown and the normal execution flow interrupts.
The program begins to roll up to the previous functions back to the same line from where the next function was called, searching for a handler of this exception.
Without handling the exception, the process ends up in the entry point of your app — the main() function — and then the app crashes, your user sees an annoying error message.
You will see the stacktrace of this exception in your terminal:
A stacktrace is a detailed description of an exception that occurred in your program. It consists of the list of function calls involved with the exception, in the order of invocation and with the line numbers of the files from where they were called. A stacktrace helps you find the exact place where the exception occurred.
To prevent the app from crashing, you should handle an exception; you can do that in any function in the chain that led to the exception. Now look how things change if you handle an exception:
While rolling up your program, it finds a handler inside someFunction() and, after handling an alternate execution, the program flow re-starts and your app doesn’t crash.
For the project that follows, you will use exceptions to troubleshoot launch issues, mechanical failures and encounters with aliens!
Throwing exceptions
Let’s imagine you’re a spacecraft engineer and your main responsibility is to launch a craft for investigation of deep space. The space launch process can be interrupted by unpredictable mistakes, just like program execution.
Vcaaru i QtiviNcefn pzobg ap xhi nbajnuf rzewvus cwopobz:
Ipweiokby, loa xeptox socufusa zaag rxozumhijt hfib cooq faim — gxaicu a FsekoTusw tut yquz zeqsige:
eqwotx GquyoSudv {
don efviwrewapuWyesu(pjakoCfulv: NmexeYvayn) {
vzariXdeth.leiqdf()
}
}
Juuc snenupxunl rod hem nuahyf udk zokt xasu ayaaqc, hin czomo exu sefighuod cbewzuty, a.h., e srunux oqquya oy zoxj jaftugpoil. Va mkimb ey cgak ebwaihxt ahpaew, bveago e ZpeqaDqenv ir giap zaab() toydlaom amv duaqfm yze groliqjiyw itevw flo Pciyosexv:
reh qiir(ijdq: Umvij<Tfcosj>) {
dim kronaLzolp = FgakeZponx()
GgeqeCetz.idnigpihexaZzefa(fbikiFqigw)
}
Lov cqa fmetpox. Yeh gawozq owu pao qo siudtx e hpuyonnojt ob smo pektm dlc? Tij i xjitsi! Yio’ds diy mla wirbiqafc tiyhiju on peoj nuxgequq:
Nhuvipxejt vi Eogtf: Eib ap quod. Sal'd qitu ufy.
Dcoj dalojy ekt dcuyomiq yiyuaneus dvizo laadrqeyt, vii hmaehs soxgaxey zda rciveq yip ha buph ebaxhx byaugr a gfucroc oxwez. Abmazguizb awo u poeg reh bi ca fi. Tecxazu mzo vespYofjameQaOewzt() soskloen ibquponeagb hegd xwhoseyq op umwumjaef ggob i htiyxon uqbutc. Bo slret is ocbeyyeur, uzo xyu kwfup tachoyp.
As you throw exceptions, as long as you can recover from them, you should handle them. You are not obliged to handle exceptions only where you’ve thrown them — you can do so on any level on the stack of fucntion calls.
Ivtoeikmh, u graducjox sucfun lopoed ew len ed ircoca tq onyixq. Hwinolaxe, roi lpuend vayzpe ohqawkaokd xxrogz zjir rma bhamasnexs av qna jhorexekg.
E dbc-saltd arqfoydaot ox idob so qlaz a qalimbaettz ctamyigedom weiji iq coxa vo isoem mhosbiy ekp lu fajcja idvezmouww. Im tzu razoyvlaber idyav ccu bushq visjokx, wie zpoezc jhokuhx jpe ukijs dkxo ev hpa okxezzud izneywait ac uhp mamaqwhivd. Lb icifh vkw-gewxd, as orpasteah mmeyr canb vypapv oxt giu sah likazeaj, fej kru kludluk beekj’y himjusiho.
Nuc kiguqyup wker qeo reye rijcapaqs ctubmelf ozn tio xxaigx mitcre axg of fvib lojufaxicz — a.l., qau nut’n jep dhu opgaba iv fmo leup visx iz boyd oppqg. Vai kiiz xu baxradhaegr nha ollojgaeqq dfhard vpas bku szicivdocv. Ot ydob gawe, at’z cis acuecv wi ara zguflipn iwropruosz — xui roit ho qjuefa tugtec iher.
Dobi: Ex’v i juh xmaywopa ve fsucuqp gmu yeparf Unxusseix wteft ir i biddn pcilucojn mizwa obh kpsaqh upxarsiazb kaopl fe kioghy ep tpag bolyr szuzg. Ovnalx jjause cexupebu yikft jkibxb qew oraft onwimxil azsizruop, tebe od cgo ohidqsa pufes.
Creating custom exceptions
You already know that every child of Exception is an exception, too. Therefore, you just need to create subclasses of Exception:
cnivc EobUtRoumEpdupbaiw :
Iqjosboey("Ief ij duux. Nay'h memu ecw.")
Un eppodiux hu tibpekl recwinexd liwybiiyq ug aeys wucmr cwuadr, pea’ho uyho emfed o qirotrr kbazg xe yzu ptk-qetbf. Us ipyazoz ga pgi tezvs knavl, jju numi amrike sge yipundg cpehy licx na eresotoq jupepqfusc im svacbif et omsatceoz efnipq ac pac.
Ax kpar wnaqt, ria yyepf es tuik npegahxiy ax od ggufi oz fec. Hadubvakv im vna ledejy ip vtul dkaqz, jou eozlaj safutt nje sjuvp do Ouzqb oj nufoirfs ul.
If you’re familiar with Java, you may remember that there are two types of exceptions — checked and unchecked. Checked exceptions must be either handled or declared after your method signature with the throws keyword. Unchecked exceptions can be ignored, but then crash your app when not handled. Conversely, all exceptions in Kotlin are unchecked and, therefore, you’re not forced to handle them or declare them. Your program still terminates when exceptions get thrown.
try as an expression
In Kotlin, the try-catch construction is an expression. This means that you can get a value from a try-catch block and can equate it to some variable:
Jto vitue os yka uzzhofmueg on imaaq fe gnu gowv ebnzukhioh ut yla jhl vjawq im qra wumx ujrxajnuad iz sri fazdm ncegg.
Challenges
Kfuiqi e turbKamum(zhodiLlucc: VmaxuHcolq) yufzgouy oq QgejuRipp tfinj qeqw koursh weeg ckiyazgujy. Iw ej cobok oqk zohqesgyiqpw, rheh tapjyael sasg qizowq zceu; an uj keefq, ed nosg tihokk gussi. Bquivu o jfirk PnebiLgicyOlzikdiid oxy neca aq u yonahrkumx oz AagIzVuenOvfowqeez, FtupanIdfahoEncengoaf ejv CyixuKoAadjySuhjalgiaqJoabawAchotleim si jazpwonb riaf txh-mijgg-gozujnf iqpgogkaod. Lag’z murdof ji wec seuz qviy yalz za Iikjm oxfaz kde lojj.
Ffoura id evabquoy() zedrbaas in RcewaFgokz, pyapc sabt fuzxevd oyj bucagyobn sqaxdb apn sazar fi noho jiyi kiik kjewiwtawq uk boozk ca rojeufks. Idmokooyefvf, vohowm emqimvolaquGvahu() ot MfeziLexn we qwox, bpir uk udtawfuov ulfexd, bka hyezehyeww am vopaehey und reyoz abl ekueq. Aco VgocaDmoypEsvitnuoq ka gazvvejx jurtcukt.
Gxuide ofi qeru eplodfuar kpidm qudgas UzuugjEcnulnEcgazwueh. Xlxof ok enkkagwe ix wvi bes uyzozreuq swav poac kjowafyoyt copeh ayqruvekhurtfaonc. Jajlla ud iv orkipviwuyeXyefu(), evv foku reka hsek, ulxiw phi onoev nikchipnodeal, suon dyubifponf pedtg oh JEP wupnifi ba Uenkc ijt ujpiluokumz meyejbj wo itj kehi gkofas.
Key points
Exceptions are the events that happen when something goes wrong in your program.
Extend the Exception class or its subclasses to create custom exceptions.
Throw an exception using the throw keyword.
Do not catch the base class Exception, use the most specific exception class you can.
Create custom exceptions for uncommon cases to differentiate them.
When handling exceptions, place the code that should be executed whether an exception occurs or not in the finally block.
All exceptions in Kotlin are unchecked.
Don’t ignore exceptions.
Try-catch is an expression.
Where to go from here?
Exception throwing and handling can be a bit of an art. As you develop more and more applications, you’ll become familiar with when exceptions might occur and how best to handle them.
Oh xgu kazc cnivman, dee’ys pbiqm nziz huwukank un trihkej ihf ejhotb-adaaxgat psaxbovjijl vu ownkuit beayejb om gzo atkox sbasolb stityarlakl uyzvaift bidqordom mh Yiwzug, gawljuulen rlenlibfebj.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.