Commit 094dad2
committed
feat: Add TryCatch demo handling division by zero with user input
WHAT the code does:
- Defines TryCatch with main() to demonstrate structured exception handling.
- Uses Scanner to read two integers d and f from user.
- Declares variables:
- a = 10, b = 0 → deliberate zero denominator.
- c and g initialized to 0 for safe compilation.
- First try–catch block:
- Attempts a / b → triggers ArithmeticException.
- Caught and prints "Error: Cannot divide a by b".
- Second try–catch block:
- Attempts d / f (user-provided values).
- If f == 0, triggers ArithmeticException.
- Caught and prints "Error: Denominator should not be zero".
- Prints "Bye" at the end, showing program continues gracefully.
WHY this matters:
- Demonstrates how try–catch blocks allow safe handling of runtime exceptions.
- Shows that different risky operations can be isolated in separate try–catch blocks.
- Highlights the difference between a pre-known division by zero (a / b) and a user-input scenario (d / f).
- Reinforces best practice of validating inputs and handling exceptions instead of letting program crash.
HOW it works:
1. Program starts, prompts user for two numbers.
2. Division a / b runs inside try:
- Since b = 0, throws ArithmeticException.
- catch block prints error message.
3. Division d / f runs with user input:
- If f ≠ 0, prints result.
- If f = 0, ArithmeticException caught, error printed.
4. Execution continues and "Bye" prints regardless of errors.
Tips and gotchas:
- Closing Scanner is good practice (done here).
- Avoid dividing without validating denominator; input checks are preferable to relying only on try–catch.
- Keep try–catch blocks as small as possible (only wrap risky code).
- Generic Exception should not be used unless necessary; catching specific exceptions is cleaner and safer.
Use-cases / analogies:
- Calculator applications: division operations need safe handling of zero denominators.
- Banking systems: avoid division errors in interest calculations or currency conversions.
- User-driven apps: exception handling ensures invalid input does not crash the system.
Short key: java exception-handling try-catch division-by-zero input-validation.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d7e6f2c commit 094dad2
1 file changed
+4
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
4 | 4 | | |
5 | 5 | | |
6 | 6 | | |
| 7 | + | |
7 | 8 | | |
8 | 9 | | |
9 | | - | |
| 10 | + | |
10 | 11 | | |
11 | 12 | | |
12 | 13 | | |
13 | | - | |
| 14 | + | |
14 | 15 | | |
15 | 16 | | |
16 | 17 | | |
| |||
20 | 21 | | |
21 | 22 | | |
22 | 23 | | |
23 | | - | |
| 24 | + | |
24 | 25 | | |
25 | 26 | | |
26 | 27 | | |
27 | 28 | | |
28 | 29 | | |
29 | 30 | | |
30 | | - | |
31 | 31 | | |
32 | 32 | | |
33 | 33 | | |
| |||
0 commit comments