Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Types
  • Array
  • String
  • Functions
  • Collections
  • Oops
  • Android
  • Android Studio
  • Kotlin Android
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
How to Throw a Custom Exception in Kotlin?
Next article icon

Exception Handling in Kotlin with Examples

Last Updated : 16 Aug, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Exceptions are the error which comes at the runtime and disrupts your flow of execution of the program. Basically exception is the unwanted event that occurs at runtime. The method by which we can handle this kind of error is called Exception Handling.

Types of Exceptions

  1. Checked Exception: Exceptions that occur at the compile-time, or we can say that checked at the compile time is called Checked Exception. Example — IOException, Some file related Exception, etc
  2. Unchecked Exception: Exceptions that occur at the runtime is called Unchecked Exception. Example — OutofBound exception.

Note: In Kotlin we have only unchecked Exceptions which only figure out at the runtime.

How to Handle Exceptions?

We have some keywords which help us to handle Exceptions.

  1. Try            // This will try to find the exception
  2. Throw      // If exception found then it will throw the exception
  3. Catch       // After throwing it will catch the exception and execute their body.

We have one more keyword called Finally, It will always execute either we got exception or not. In this, we have some important codes that always need to execute.

Note: If the program exit by exitProcess(Int) or abort(), then the finally will not be executed.

How to Use try-catch and finally?

try
{
  // your code which
  // may throw an exception
}
catch(ex : ExceptionName)
{
  // Exception handle code
}
finally
{
  // this will execute every time
  // either we found exception or not
}
                      
                       

Example 1: Divide By Zero 

Kotlin

fun main()
{
    try
      {
      // calling the function
      divide(10, 0) 
    }
    catch (ex : Exception)
    {
      // or you can also write your
      // own handle here
      println(ex.message) 
    }
}
  
// function which may give exception
fun divide(a : Int, b : Int)
{
    if (b == 0)
        throw Exception("Divide by zero") 
    // even if you didn't write
    // this throw it will work fine.
    println("Division is :" + a / b)
}
                      
                       

Output:

Divide by zero  

Example 2: Let’s try the same code with try-catch and finally.

Kotlin

fun main()
{
    // first try block
    try 
    {
      // didn't throw any exception
      divide(20, 10) 
    }
    catch (ex : Exception)
    {
      // or you can also write your
      // own handle here
      println(ex.message) 
    }
    finally 
    {
      println("I'm executed")
    }
      
    // 2nd try block
    try 
    {
      // throw an exception
      divide(10, 0) 
    }
    catch (ex : Exception)
    {
      // or you can also write your
      // own handle here
      println(ex.message) 
    }
    finally 
    {
      println("I'm executed")
    }
}
  
fun divide(a : Int, b : Int)
{
    if (b == 0)
        throw Exception("Divide by zero") 
    println("Division is :" + a / b)
}
                      
                       

Output:

Division is : 2  I'm executed  Divide by zero  I'm executed  

Note that In the above example, finally is executed in both cases either exception occurs or not.



Next Article
How to Throw a Custom Exception in Kotlin?
author
iamabhishekkalra
Improve
Article Tags :
  • Kotlin
  • Kotlin Exception-Handling

Similar Reads

  • Exception Handling in Kotlin Coroutines
    Coroutines are a new way for us to do asynchronous programming in Kotlin in Android. When developing a production-ready app, we want to ensure that all exceptions are handled correctly so that users have a pleasant experience while using our app. In this article, we will discuss how to properly hand
    7 min read
  • Exception handling in Objective-C
    Exception handling is an essential aspect of Objective-C programming, enabling developers to manage unforeseen errors effectively. Objective-C provides a robust set of tools and methodologies to handle exceptions, ensuring the stability and reliability of applications. Let's delve deeper into the nu
    5 min read
  • Kotlin Function Variations With Examples
    While defining a function in Kotlin we have many optional annotations. We will learn each of them one by one. Defining a function in Kotlin: Visibility modifier fun functionName (argument name: type name, ...): return type{ ..... // function body ..... return value } Normally, It is the proper way f
    3 min read
  • Exception Handling in Programming
    Exception handling is a critical aspect of programming, enabling developers to manage unexpected or erroneous situations gracefully. In this article, we'll discuss the concept of exception handling, its importance, and best practices for implementing it effectively in various programming languages.
    7 min read
  • How to Throw a Custom Exception in Kotlin?
    In addition to the built-in Exception Classes, you can create your own type of Exception that reflects your own cause of the exception. And you will appreciate the use of Custom Exception when you have multiple catch blocks for your try expression and can differentiate the custom exception from regu
    2 min read
  • Kotlin Exception Handling | try, catch, throw and finally
    An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program. Th
    6 min read
  • use Keyword in Kotlin with Example
    Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a “better
    3 min read
  • Kotlin partition() Method with Examples
    In this article, we are going to discuss how to split the original collection into pair of collections, because sometimes while coding, you wish that you could just split a list into sublists without going into the for and while loops. Kotlin provides you with a function just for this occasion. In t
    4 min read
  • Kotlin Flow in Android with Example
    Kotlin Flow is one of the latest addition to the Kotlin Coroutines. With Kotlin Flow we can handle streams of data asynchronously which is being executed sequentially.  What are we going to build in this article? We will build a simple app that fetches some data from API and shows it on the screen.
    8 min read
  • Spring MVC - Exception Handling
    Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences