0
0
Javaprogramming~20 mins

Throw keyword in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Throw Keyword in Java
πŸ“– Scenario: You are creating a simple banking application. You want to make sure that users cannot withdraw more money than they have in their account.
🎯 Goal: Build a Java program that uses the throw keyword to stop the program and show an error message if a user tries to withdraw too much money.
πŸ“‹ What You'll Learn
Create a variable to hold the current account balance.
Create a variable to hold the amount to withdraw.
Use the throw keyword to raise an exception if the withdrawal amount is greater than the balance.
Print a message showing the remaining balance if the withdrawal is allowed.
πŸ’‘ Why This Matters
🌍 Real World
Banking apps and many other programs use exceptions to stop errors and keep data safe.
πŸ’Ό Career
Knowing how to use <code>throw</code> helps you write safer Java programs that handle mistakes properly.
Progress0 / 4 steps
1
Set up account balance and withdrawal amount
Create a variable called balance and set it to 500. Create another variable called withdrawAmount and set it to 600.
Java
Need a hint?

Use int to create whole number variables.

2
Prepare to check withdrawal
Create a variable called errorMessage and set it to the string "Insufficient funds".
Java
Need a hint?

Use String to store text messages.

3
Use throw to stop withdrawal if funds are low
Write an if statement that checks if withdrawAmount is greater than balance. Inside the if, use throw new IllegalArgumentException(errorMessage); to stop the program with the error message.
Java
Need a hint?

The throw keyword is used to raise an exception and stop the program.

4
Show remaining balance if withdrawal allowed
Write a System.out.println statement that prints "Remaining balance: " plus the result of balance - withdrawAmount.
Java
Need a hint?

If the withdrawal is too big, the program will stop and show the error message.