Custom Checked Exception
Completed
Create class InsufficientFundsException extends Exception. A withdraw method declares throws InsufficientFundsException with message short by X. Start with balance 100, process withdrawals, and print the new balance or failed: MESSAGE.
Input
n, then n amounts.
Output
n lines.
Example
Input
3 30 90 70
Output
70 failed: short by 20 0
Editor
Java
Hints
Checked exceptions (extending Exception) must be declared with throws or caught.
RuntimeException subclasses are unchecked.
Solution explanation
Checked exceptions force callers to deal with recoverable failures; the compiler won't let them forget.
Show solution
import java.util.Scanner;
class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
public class Main {
static int balance;
static void withdraw(int amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("short by " + (amount - balance));
}
balance -= amount;
}
public static void main(String[] args) {
balance = 100;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
try {
withdraw(sc.nextInt());
System.out.println(balance);
} catch (InsufficientFundsException e) {
System.out.println("failed: " + e.getMessage());
}
}
}
}