-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionHandling.java
More file actions
38 lines (34 loc) · 1.2 KB
/
ExceptionHandling.java
File metadata and controls
38 lines (34 loc) · 1.2 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
public class ExceptionHandling {
public static void main(String[] args) {
// Example of handling an exception using try-catch
try {
int result = divide(10, 0); // This will cause an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
// Example of a custom exception
try {
validateAge(15); // This will throw a custom exception
} catch (AgeNotValidException e) {
System.out.println("Error: " + e.getMessage());
}
}
// Method to divide two numbers
public static int divide(int a, int b) {
return a / b; // This may throw ArithmeticException if b is zero
}
// Method to validate age
public static void validateAge(int age) throws AgeNotValidException {
if (age < 18) {
throw new AgeNotValidException("Age must be 18 or older.");
}
System.out.println("Age is valid.");
}
}
// Custom exception class
class AgeNotValidException extends Exception {
public AgeNotValidException(String message) {
super(message);
}
}