Commit 36726f8
committed
feat: Demonstrate handling of ArithmeticException with try–catch block
WHAT the code does:
- Defines ExceptionDemo with main():
- Declares integers a = 10, b = 0.
- Attempts c = a / b inside a try block.
- Division by zero triggers ArithmeticException.
- Catch block handles exception, printing user-friendly message plus exception details.
- Program continues execution and prints "Bye".
WHY this matters:
- Shows how **try–catch** prevents abrupt program termination.
- Without try–catch:
- Division by zero causes runtime crash.
- Program terminates, and subsequent lines never execute.
- With try–catch:
- Exception is caught.
- Custom message is displayed.
- Program resumes normally after the catch block.
HOW it works:
1. Execution enters try block.
2. a / b attempts 10 / 0 → triggers ArithmeticException.
3. JVM looks for matching catch block → finds ArithmeticException catch.
4. Prints "Denominator should not be Zero(0) try again: java.lang.ArithmeticException: / by zero".
5. Control resumes after catch → prints "Bye".
Tips and gotchas:
- Always catch the most specific exception possible (ArithmeticException is appropriate here).
- Printing exception e provides both message and exception type.
- Avoid catching generic Exception unless you intend to handle all errors.
- Use Scanner or user input in real scenarios to retry with valid denominator.
- Exception handling should be for exceptional cases, not routine control flow.
Use-cases / analogies:
- Like an airbag: exception handling cushions the crash (division by zero) and allows the program (car) to continue safely.
- In calculators: prevents program from freezing when user divides by zero.
Short key: java exceptions try-catch arithmetic divide-by-zero safe-execution.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 690d444 commit 36726f8
1 file changed
+3
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
10 | 10 | | |
11 | 11 | | |
12 | 12 | | |
13 | | - | |
14 | | - | |
| 13 | + | |
15 | 14 | | |
16 | 15 | | |
17 | 16 | | |
18 | 17 | | |
19 | 18 | | |
20 | 19 | | |
21 | | - | |
22 | | - | |
| 20 | + | |
23 | 21 | | |
24 | 22 | | |
25 | 23 | | |
26 | 24 | | |
27 | | - | |
| 25 | + | |
0 commit comments