0
0
Javaprogramming~30 mins

Exception propagation in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
Exception Propagation in Java
πŸ“– Scenario: Imagine you are building a simple banking application. You want to check if a withdrawal amount is valid. If the amount is negative, an exception should be thrown and passed up the call chain until it is handled.
🎯 Goal: Build a Java program that demonstrates how exceptions can be thrown in one method and caught in another method higher up the call stack.
πŸ“‹ What You'll Learn
Create a method that throws an exception when a negative withdrawal amount is passed
Create a method that calls the first method and propagates the exception
Handle the exception in the main method
Print a message when the exception is caught
πŸ’‘ Why This Matters
🌍 Real World
Exception propagation is used in real-world applications to handle errors like invalid inputs or failed operations without crashing the program immediately.
πŸ’Ό Career
Understanding exception propagation is essential for writing robust Java applications and is a common topic in software development interviews.
Progress0 / 4 steps
1
Create the withdraw method that throws an exception
Create a method called withdraw that takes an int amount parameter. If amount is less than 0, throw a new IllegalArgumentException with the message "Negative amount not allowed".
Java
Need a hint?

Use throw new IllegalArgumentException("Negative amount not allowed") inside an if statement checking if amount < 0.

2
Create the processWithdrawal method that calls withdraw
Create a method called processWithdrawal that takes an int amount parameter and calls the withdraw method with this amount. Do not handle the exception here; let it propagate.
Java
Need a hint?

Simply call withdraw(amount) inside processWithdrawal without try-catch.

3
Call processWithdrawal from main and handle the exception
In the main method, call processWithdrawal with the value -100. Use a try-catch block to catch IllegalArgumentException and print "Exception caught: " followed by the exception message.
Java
Need a hint?

Use try and catch (IllegalArgumentException e) around the call to processWithdrawal(-100). Print the message with System.out.println.

4
Print the final output
Run the program and print the output that shows the exception message caught in main.
Java
Need a hint?

Run the program to see the exception message printed from the catch block.