Skip to content

Commit 36726f8

Browse files
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

File tree

1 file changed

+3
-5
lines changed

1 file changed

+3
-5
lines changed

Section18ExceptionHandling/src/ExceptionDemo.java

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,16 @@ public static void main(String[] args) {
1010
c = a / b;
1111
/*
1212
This is without a try catch block.
13-
14-
Program terminiate and not printing rest of the statements.n
13+
Program terminates and does not print the rest of the statements.n
1514
Exception in thread "main" java.lang.ArithmeticException: / by zero
1615
at ExceptionDemo.main(ExceptionDemo.java:7)
1716
*/
1817

1918
System.out.println(c);
2019
}
21-
catch (ArithmeticException e)
22-
{
20+
catch (ArithmeticException e) {
2321
System.out.println("Denominator should not be Zero(0) try again: "+e);
2422
}
2523
System.out.println("Bye");
2624
}
27-
}
25+
}

0 commit comments

Comments
 (0)