-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomExceptions.java
More file actions
69 lines (53 loc) · 1.97 KB
/
Copy pathCustomExceptions.java
File metadata and controls
69 lines (53 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package exceptions;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Custom exceptions, creating our own business logic error types
*/
// Checked exception: Forces the caller to handle or declare it (extends Exception)
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// Unchecked exception: Does not force the caller to handle it (extends RuntimeException)
class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
BankAccount(double initialBalance) {
this.balance = initialBalance;
}
void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
// Checked exception: It must be declared in the method signature or handled in the caller
throw new InsufficientBalanceException("Insufficient balance. Available: " + balance);
}
balance -= amount;
}
}
public class CustomExceptions {
private static final Logger logger = Logger.getLogger(CustomExceptions.class.getName());
// Unchecked exception: It does not need to be declared or handled
static void validateAge(int age) {
if (age < 0 || age > 120) {
throw new InvalidAgeException("The age " + age + " is not valid.");
}
}
public static void main() {
BankAccount account = new BankAccount(100);
try {
account.withdraw(500); // Triggers InsufficientBalanceException
} catch (InsufficientBalanceException e) {
logger.log(Level.SEVERE, "Operation rejected: {0}", e.getMessage());
}
try {
validateAge(150); // Triggers InvalidAgeException (unchecked)
} catch (InvalidAgeException e) {
logger.log(Level.SEVERE, "Invalid data: {0}", e.getMessage());
}
}
}