Commit e23e412
committed
feat: Demonstrate multiple try–catch blocks for safe division handling
WHAT the code does:
- Defines ExceptionHandling with main():
- Uses Scanner to take two integers from user (d, f).
- Declares variables a = 10, b = 0.
- Performs two divisions with separate exception handling:
1. a / b:
- Always triggers ArithmeticException (division by zero).
- Caught and prints error message.
2. d / f:
- Depends on user input.
- If f = 0 → ArithmeticException caught.
- Else prints result.
- Prints "Bye" to confirm graceful program termination.
- Closes Scanner.
WHY this matters:
- Demonstrates handling multiple potential exceptions **independently**.
- Ensures that failure in one calculation doesn’t prevent the program from continuing to the next.
- Reinforces exception handling as a tool to keep applications robust and user-friendly.
HOW it works:
1. First try–catch:
- Attempts 10 / 0.
- ArithmeticException caught → prints "Error: Cannot divide a by b…".
2. Second try–catch:
- Attempts d / f with user-provided values.
- If denominator f = 0 → prints "Error: Denominator should not be zero…".
- Else prints correct result.
3. Program continues execution to "Bye".
Tips and gotchas:
- Each risky operation should have its own try–catch for precise handling.
- Multiple exceptions can be caught in one block using multi-catch (e.g., `catch (ArithmeticException | InputMismatchException e)`).
- Always close Scanner (done here) to avoid resource leaks.
- Avoid using exceptions for routine control flow—validate input before dividing when possible.
Use-cases / analogies:
- Like two test flights: if one plane fails (division by zero), the other test (user input division) can still proceed independently.
- In calculators or banking systems: prevents system crash when invalid division occurs, while allowing other operations to continue.
Short key: java exception-handling multiple-try-catch arithmetic divide-by-zero input-validation.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 36726f8 commit e23e412
1 file changed
+11
-10
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
3 | 3 | | |
4 | 4 | | |
5 | 5 | | |
| 6 | + | |
6 | 7 | | |
| 8 | + | |
7 | 9 | | |
8 | 10 | | |
9 | | - | |
| 11 | + | |
10 | 12 | | |
11 | 13 | | |
12 | 14 | | |
13 | | - | |
| 15 | + | |
14 | 16 | | |
15 | 17 | | |
16 | | - | |
17 | | - | |
| 18 | + | |
18 | 19 | | |
19 | 20 | | |
20 | 21 | | |
21 | | - | |
22 | | - | |
| 22 | + | |
| 23 | + | |
23 | 24 | | |
24 | 25 | | |
25 | 26 | | |
26 | 27 | | |
27 | | - | |
28 | | - | |
| 28 | + | |
29 | 29 | | |
30 | 30 | | |
31 | 31 | | |
32 | | - | |
33 | | - | |
| 32 | + | |
| 33 | + | |
34 | 34 | | |
35 | 35 | | |
| 36 | + | |
36 | 37 | | |
37 | 38 | | |
38 | 39 | | |
| |||
0 commit comments