From af6d532ea08460c477ba16ede0324d88e60edb6c Mon Sep 17 00:00:00 2001 From: Jose De La Cruz Date: Thu, 4 Jun 2026 07:42:11 -0400 Subject: [PATCH] Completed exceptions exercise --- .../_10_exceptions/CustomException.java | 60 ++++++++++++++++++- .../InsufficientFundsException.java | 14 +++++ .../_10_exceptions/TryCatch.java | 48 ++++++++++++--- 3 files changed, 112 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/amigoscode/_2_developers/_10_exceptions/InsufficientFundsException.java diff --git a/src/main/java/com/amigoscode/_2_developers/_10_exceptions/CustomException.java b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/CustomException.java index d9387f2..cae9dbb 100644 --- a/src/main/java/com/amigoscode/_2_developers/_10_exceptions/CustomException.java +++ b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/CustomException.java @@ -2,7 +2,7 @@ /** * Custom Exception Exercises - * + *

* Practice creating custom checked and unchecked exceptions, throwing them * from methods, catching them, and using exception chaining. */ @@ -25,6 +25,15 @@ public class CustomException { // - Have a constructor that takes a String message and a Throwable cause, // and calls super(message, cause) // Define it as a static inner class here. + public static class InvalidAgeException extends RuntimeException { + public InvalidAgeException(String message) { + super(message); + } + + public InvalidAgeException(String message, Throwable cause) { + super(message, cause); + } + } // TODO: 3 - Create a static inner class BankAccount with: @@ -35,11 +44,38 @@ public class CustomException { // message and the shortfall amount (amount - balance). // Otherwise, subtract amount from balance. // - A method: double getBalance() + public static class BankAccount { + private double balance; + + public BankAccount(double initialBalance) { + this.balance = initialBalance; + } + + public void withdraw(double amount) throws InsufficientFundsException { + if (amount > this.balance) { + throw new InsufficientFundsException("The amount you entered is larger than your current balance", + (amount - this.balance)); + } + + this.balance = amount - this.balance; + } + + public double getBalance() { + return this.balance; + } + } // TODO: 4 - Create a static method: void validateAge(int age) // If age < 0 or age > 150, throw a new InvalidAgeException with an appropriate message. // Otherwise, print "Age " + age + " is valid." + public static void validateAge(int age) { + if (age < 0 || age > 150) { + throw new InvalidAgeException("Age is greater than or less than the provided age range of 0 to 150"); + } + + System.out.println("Age " + age + " is valid."); + } public static void main(String[] args) { @@ -50,7 +86,18 @@ public static void main(String[] args) { // Catch the exception and print its message and the shortage amount. // Also try validateAge with valid (25) and invalid (-5) values, // catching InvalidAgeException. + BankAccount myAccount = new BankAccount(100); + try { + myAccount.withdraw(50); + System.out.println(myAccount.getBalance()); + myAccount.withdraw(75); + System.out.println(myAccount.getBalance()); + validateAge(25); + validateAge(-5); + } catch (InsufficientFundsException | InvalidAgeException e) { + System.out.println("Exception: " + e.getClass().getSimpleName() + "-" + e.getMessage()); + } System.out.println("\n=== Exception Chaining ==="); // TODO: 6 - Demonstrate exception chaining: @@ -61,6 +108,15 @@ public static void main(String[] args) { // In an outer try-catch, catch the InvalidAgeException and print: // - The exception message // - The cause (using getCause()) - + try { + try { + System.out.println(Integer.parseInt("abc")); + } catch (NumberFormatException e) { + throw new InvalidAgeException("Age must be a valid number", e); + } + } catch(InvalidAgeException e) { + System.out.println("Exception message: " + e.getMessage()); + System.out.println("Cause: " + e.getCause()); + } } } diff --git a/src/main/java/com/amigoscode/_2_developers/_10_exceptions/InsufficientFundsException.java b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/InsufficientFundsException.java new file mode 100644 index 0000000..816684d --- /dev/null +++ b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/InsufficientFundsException.java @@ -0,0 +1,14 @@ +package com.amigoscode._2_developers._10_exceptions; + +public class InsufficientFundsException extends Exception { + private final double amount; + + public InsufficientFundsException(String message, double amount) { + super(message); + this.amount = amount; + } + + public double getAmount() { + return this.amount; + } +} diff --git a/src/main/java/com/amigoscode/_2_developers/_10_exceptions/TryCatch.java b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/TryCatch.java index afefa02..c4e97b0 100644 --- a/src/main/java/com/amigoscode/_2_developers/_10_exceptions/TryCatch.java +++ b/src/main/java/com/amigoscode/_2_developers/_10_exceptions/TryCatch.java @@ -4,7 +4,7 @@ /** * Try-Catch Exercises - * + *

* Practice exception handling: try-catch, finally, multi-catch, try-with-resources, * throwing exceptions, and exception propagation. */ @@ -23,7 +23,12 @@ public static int safeArrayAccess(int[] arr, int index) { // try to return arr[index]. // catch ArrayIndexOutOfBoundsException, print "Index out of bounds: " + index, // and return -1. - return 0; + try { + return arr[index]; + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println("Index out of bounds: " + index); + return -1; + } } /** @@ -36,7 +41,12 @@ public static int safeArrayAccess(int[] arr, int index) { public static int safeParseInt(String text) { // TODO: 2 - Wrap Integer.parseInt(text) in a try-catch block. // catch NumberFormatException, print "Cannot parse: " + text, and return 0. - return 0; + try { + return Integer.parseInt(text); + } catch (NumberFormatException e) { + System.out.println("Cannot parse: " + text); + return 0; + } } /** @@ -54,6 +64,13 @@ public static int divideWithFinally(int a, int b) { // finally: print "Division operation completed." // Return the result. (You'll need a local variable since return in try // executes after finally.) + try { + return a/b; + } catch(ArithmeticException e) { + System.out.println("Cannot divide by zero!"); + } finally { + System.out.println("Division operation completed."); + } return 0; } @@ -72,6 +89,12 @@ public static int multiCatchDemo(String[] data, int index) { // Catch both ArrayIndexOutOfBoundsException and NumberFormatException // in a single catch block using: catch (ExType1 | ExType2 e) // Print "Error: " + e.getMessage() and return -1. + try { + String element = data[index]; + return Integer.parseInt(element); + } catch(ArrayIndexOutOfBoundsException | NumberFormatException e) { + System.out.println(e.getMessage()); + } return 0; } @@ -89,7 +112,12 @@ public static int tryWithResourcesDemo(String input) { // } // catch any exception and return -1. // The Scanner will be automatically closed after the try block. - return 0; + try (Scanner scanner = new Scanner(input)) { + return scanner.nextInt(); + } catch(Exception e) { + System.out.println(e.getMessage()); + return -1; + } } /** @@ -99,10 +127,13 @@ public static int tryWithResourcesDemo(String input) { * @return the validated age * @throws IllegalArgumentException if age is negative */ - public static int validateAge(int age) { + public static int validateAge(int age) throws IllegalArgumentException{ // TODO: 6 - If age < 0, throw a new IllegalArgumentException // with the message "Age cannot be negative: " + age. // Otherwise, return age. + if (age < 0) { + throw new IllegalArgumentException("Age cannot be negative: " + age); + } return age; } @@ -112,7 +143,7 @@ public static int validateAge(int age) { * * @param value a string that should contain a positive number * @return the validated positive number - * @throws NumberFormatException if value is not a number + * @throws NumberFormatException if value is not a number * @throws IllegalArgumentException if the number is negative */ public static int processValue(String value) { @@ -120,7 +151,7 @@ public static int processValue(String value) { // Then call validateAge() with the parsed int. // Do NOT catch any exceptions here — let them propagate to the caller. // This demonstrates that exceptions travel up the call stack. - return 0; + return validateAge(Integer.parseInt(value)); } public static void main(String[] args) { @@ -133,7 +164,6 @@ public static void main(String[] args) { System.out.println("\n=== Safe Parse Int ==="); System.out.println("Parse '42': " + safeParseInt("42")); System.out.println("Parse 'abc': " + safeParseInt("abc")); - System.out.println("\n=== Finally Block ==="); System.out.println("10 / 2 = " + divideWithFinally(10, 2)); System.out.println("10 / 0 = " + divideWithFinally(10, 0)); @@ -148,6 +178,7 @@ public static void main(String[] args) { System.out.println("Parse '123': " + tryWithResourcesDemo("123")); System.out.println("Parse 'xyz': " + tryWithResourcesDemo("xyz")); + System.out.println("\n=== Throw Exception ==="); try { validateAge(25); @@ -164,5 +195,6 @@ public static void main(String[] args) { } catch (Exception e) { System.out.println("Propagated exception: " + e.getClass().getSimpleName() + " - " + e.getMessage()); } + } }