From the course: Build Spring Boot Apps with the Kotlin Programming Language

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

try as an expression

try as an expression

- [Instructor] So we've already seen that you can create a try-catch block, just as you do in Java, but there is extra difference, and that is that in Kotlin, just like the F-statement, the try-statement is an expression. In other words, it can return a value. So for example, suppose we had a variable, let's call it results. And I want to set the result to five divided by 23. But I know that this five divided by 23 could throw an exception. Well, what I can do is, say, if it throws an exception, I want the result to be zero. I can put this in a try-catch block. I can say my result is going to be equal to, let's try doing divide five by 23, and we'll catch, well actually I want to catch any type of exception, so I'm going to say, it's E of type exception, and if an exception occurs, no matter what the exception is then our result variable is going to preset equal to zero. So now we can println this out (keyboard clicking) and this first time around we should get a number because there…

Contents