Set age checks its input. If the age is impossible, it throws a new illegal argument exception, with a helpful message. Throw stops the method straight away. Main catches it, and prints the message. Run it. Thirty is accepted. Minus four is rejected, with a clear reason.
Main.javajava
public class Main { static void setAge(int age) { if (age < 0 || age > 150) { throw new IllegalArgumentException("Age must be 0-150, got " + age); } System.out.println("Age set to " + age); } public static void main(String[] args) { setAge(30); try { setAge(-4); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); } }}
You can make your own exception class, by extending Exception. Its constructor builds a message, and passes it to super. The name itself explains the problem, insufficient funds.
Main.javajava
public class InsufficientFundsException extends Exception { public InsufficientFundsException(double needed) { super("Not enough money. Short by " + needed); }}
Pay declares that it throws our exception. If the amount is too much, it throws. Main catches it. Run it. Fifteen is paid, leaving five. Paying twelve is too much, and we're short by seven.
Main.javajava
public class Main { static double balance = 20; static void pay(double amount) throws InsufficientFundsException { if (amount > balance) throw new InsufficientFundsException(amount - balance); balance -= amount; System.out.println("Paid " + amount + ", left " + balance); } public static void main(String[] args) { try { pay(15); pay(12); } catch (InsufficientFundsException e) { System.out.println(e.getMessage()); } }}
Output
Paid 15.0, left 5.0
Not enough money. Short by 7.0
Also uses InsufficientFundsException.java
public class InsufficientFundsException extends Exception { public InsufficientFundsException(double needed) { super("Not enough money. Short by " + needed); }}