Theoretical Paper
- Computer Organization
- Data Structure
- Digital Electronics
- Object Oriented Programming
- Discrete Mathematics
- Graph Theory
- Operating Systems
- Software Engineering
- Computer Graphics
- Database Management System
- Operation Research
- Computer Networking
- Image Processing
- Internet Technologies
- Micro Processor
- E-Commerce & ERP
- Dart Programming
- Flutter Tutorial
- Numerical Methods Tutorials
- Flutter Tutorials
- Kotlin Tutorial
Practical Paper
Industrial Training
Kotlin Finally Block
Kotlin finally block such block which is always executes whether exception is handled or not. So it is used to execute important code statement.
Kotlin finally Block Example 1
Let's see an example of exception handling in which exception does not occur.
fun main (args: Array< String>){ try { val data = 10 / 5 println(data) } catch (e: NullPointerException) { println(e) } finally { println("finally block always executes") } println("below codes...") } fun main (args: Array< String>){ try { val data = 10 / 5 println(data) } catch (e: NullPointerException) { println(e) } finally { println("finally block always executes") } println("below codes...") }Output:
2 finally block always executes below codes...
Kotlin finally Block Example 2
Let's see an example of exception handling in which exception occurs but not handled.
fun main (args: Array< String>){ try { val data = 5 / 0 println(data) } catch (e: NullPointerException) { println(e) } finally { println("finally block always executes") } println("below codes...") } fun main (args: Array< String>){ try { val data = 5 / 0 println(data) } catch (e: NullPointerException) { println(e) } finally { println("finally block always executes") } println("below codes...") }
Output:
finally block always executes Exception in thread "main" java.lang.ArithmeticException: / by zero
Kotlin finally Block Example 3
Let's see an example of exception handling in which exception occurs and handled.
fun main (args: Array< String>){ try { val data = 5 / 0 println(data) } catch (e: ArithmeticException) { println(e) } finally { println("finally block always executes") } println("below codes...") } fun main (args: Array< String>){ try { val data = 5 / 0 println(data) } catch (e: ArithmeticException) { println(e) } finally { println("finally block always executes") } println("below codes...") }
Output:
java.lang.ArithmeticException: / by zero finally block always executes below codes...