Commit 1ff7dcc
committed
feat: Add TryCatch1 demo showcasing parse error with finally block
WHAT the code does:
- Defines TryCatch1 with main() method.
- Inside try block:
- Attempts to parse string "Pants" into an integer using Integer.parseInt().
- This throws NumberFormatException at runtime.
- catch block:
- Catches generic Exception (covers NumberFormatException).
- Prints custom error message: "He Dude, you can't make an int out off that. Stop trying to make it happens".
- finally block:
- Executes regardless of exception outcome.
- Prints "Always executed in the finally block".
- Program continues and prints "End Here" after try–catch–finally.
WHY this matters:
- Demonstrates the difference between try, catch, and finally:
- try: contains risky code.
- catch: handles exceptions if they occur.
- finally: always executes, useful for cleanup tasks (closing files, releasing resources).
- Highlights a common runtime error: NumberFormatException when parsing invalid input.
- Shows that program flow continues gracefully after exception handling.
HOW it works:
1. try runs Integer.parseInt("Pants").
2. Fails with NumberFormatException → caught by catch(Exception e).
3. Custom error message is printed.
4. finally block executes → prints its message.
5. Execution continues after try–catch–finally → prints "End Here".
Tips and gotchas:
- Always prefer catching specific exceptions (e.g., NumberFormatException) instead of generic Exception.
- finally is best used for cleanup (closing files, network sockets, database connections).
- If System.exit() is called inside try or catch, finally may not execute.
- Messages in catch should be user-friendly for UI code, or technical/log-friendly for backend code.
Use-cases / analogies:
- Parsing user input into numbers (e.g., entering age or price).
- Converting strings from files or databases into integers safely.
- Ensuring resources (files, sockets) close even if an error occurs.
Short key: java try-catch-finally numberformatexception input-parsing cleanup.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 094dad2 commit 1ff7dcc
1 file changed
+6
-6
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
| 3 | + | |
5 | 4 | | |
6 | 5 | | |
7 | | - | |
8 | | - | |
| 6 | + | |
| 7 | + | |
9 | 8 | | |
10 | 9 | | |
11 | | - | |
12 | | - | |
| 10 | + | |
| 11 | + | |
13 | 12 | | |
14 | 13 | | |
| 14 | + | |
15 | 15 | | |
16 | 16 | | |
17 | 17 | | |
0 commit comments