Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

/**
* Custom Exception Exercises
*
* <p>
* Practice creating custom checked and unchecked exceptions, throwing them
* from methods, catching them, and using exception chaining.
*/
Expand All @@ -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:
Expand All @@ -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) {
Expand All @@ -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:
Expand All @@ -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());
}
}
}
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

/**
* Try-Catch Exercises
*
* <p>
* Practice exception handling: try-catch, finally, multi-catch, try-with-resources,
* throwing exceptions, and exception propagation.
*/
Expand All @@ -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;
}
}

/**
Expand All @@ -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;
}
}

/**
Expand All @@ -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;
}

Expand All @@ -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;
}

Expand All @@ -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;
}
}

/**
Expand All @@ -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;
}

Expand All @@ -112,15 +143,15 @@ 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) {
// TODO: 7 - Parse the value to an int using Integer.parseInt(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) {
Expand All @@ -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));
Expand All @@ -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);
Expand All @@ -164,5 +195,6 @@ public static void main(String[] args) {
} catch (Exception e) {
System.out.println("Propagated exception: " + e.getClass().getSimpleName() + " - " + e.getMessage());
}

}
}