Commit b1357da
committed
feat: Demonstrate checked exceptions vs runtime errors in method chaining
WHAT the code does:
- Defines class CheckedException with three static methods:
- fun1():
- Commented code shows creation of FileInputStream with "My.txt".
- Would throw a **checked exception** (FileNotFoundException), which must be handled with try–catch or declared with throws.
- fun2(): calls fun1().
- fun3(): recursively calls itself without a base case, leading to infinite recursion and eventually StackOverflowError.
- main(): calls fun3(), causing StackOverflowError at runtime.
WHY this matters:
- Shows difference between **checked exceptions** and **unchecked errors**:
- Checked exceptions:
- Caught or declared at compile-time (e.g., FileNotFoundException, SQLException).
- Example: FileInputStream requires handling since file might not exist.
- Unchecked exceptions/errors:
- Occur at runtime, not enforced by compiler (e.g., NullPointerException, StackOverflowError).
- fun3 demonstrates uncontrolled recursion leading to StackOverflowError.
- Highlights how compiler enforces handling for checked exceptions but allows recursive calls that may crash at runtime.
HOW it works:
1. If FileInputStream in fun1 were uncommented:
- Compilation fails unless code is wrapped in try–catch or method signature declares `throws FileNotFoundException`.
2. fun3():
- Calls itself infinitely.
- JVM stack memory fills up.
- Throws StackOverflowError (unchecked, subclass of Error).
3. main():
- Directly triggers fun3(), causing program crash at runtime.
Tips and gotchas:
- Always handle checked exceptions with try–catch or propagate them with throws.
- Recursion requires a base case to terminate; otherwise stack overflow occurs.
- StackOverflowError cannot be caught meaningfully for recovery; fix logic instead.
- Checked exceptions = compile-time obligation; unchecked exceptions = runtime responsibility.
Use-cases / analogies:
- Checked exceptions: like airport security requiring you to handle your luggage before boarding (must handle before runtime).
- Unchecked errors: like falling asleep while driving — compiler doesn’t stop you, but program (car) crashes at runtime.
Short key: java exceptions checked-vs-unchecked fileinputstream stackoverflow recursion.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent e989d86 commit b1357da
1 file changed
+7
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
| 3 | + | |
5 | 4 | | |
6 | 5 | | |
7 | 6 | | |
8 | 7 | | |
9 | 8 | | |
10 | 9 | | |
11 | | - | |
12 | | - | |
| 10 | + | |
| 11 | + | |
13 | 12 | | |
14 | 13 | | |
15 | | - | |
16 | | - | |
| 14 | + | |
| 15 | + | |
17 | 16 | | |
18 | 17 | | |
| 18 | + | |
19 | 19 | | |
20 | 20 | | |
21 | 21 | | |
22 | | - | |
| 22 | + | |
0 commit comments