0
0
Kotlinprogramming~30 mins

Custom exception classes in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Exception Classes in Kotlin
📖 Scenario: You are building a simple banking app. You want to handle errors clearly when someone tries to withdraw more money than they have.
🎯 Goal: Create a custom exception class called InsufficientFundsException and use it to show a clear error message when a withdrawal is too large.
📋 What You'll Learn
Create a custom exception class named InsufficientFundsException that inherits from Exception
Create a variable balance with the value 1000
Create a variable withdrawAmount with the value 1500
Write a function withdraw that throws InsufficientFundsException if withdrawAmount is greater than balance
Use a try-catch block to call withdraw and print the exception message
💡 Why This Matters
🌍 Real World
Custom exceptions help apps handle errors clearly, like showing a message when a bank withdrawal fails.
💼 Career
Understanding custom exceptions is important for writing robust Kotlin applications in jobs like Android development or backend services.
Progress0 / 4 steps
1
Create the initial variables
Create a variable called balance and set it to 1000. Then create a variable called withdrawAmount and set it to 1500.
Kotlin
Need a hint?

Use val to create variables and assign the exact numbers.

2
Create the custom exception class
Create a custom exception class called InsufficientFundsException that inherits from Exception. It should accept a message parameter of type String and pass it to the superclass.
Kotlin
Need a hint?

Define a class with class InsufficientFundsException(message: String) : Exception(message).

3
Write the withdraw function with exception
Write a function called withdraw that takes no parameters. Inside, check if withdrawAmount is greater than balance. If yes, throw InsufficientFundsException with the message "Not enough balance". Otherwise, print "Withdrawal successful".
Kotlin
Need a hint?

Use throw to raise the exception inside the if condition.

4
Call withdraw with try-catch and print error
Use a try-catch block to call the withdraw() function. Catch InsufficientFundsException and print its message.
Kotlin
Need a hint?

Use try { withdraw() } and catch (e: InsufficientFundsException) { println(e.message) }.