Skip to content

Commit 1ff7dcc

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

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
public class TryCatch1 {
22
public static void main(String[] args) {
3-
try
4-
{
3+
try {
54
int myInt = Integer.parseInt("Pants");
65
}
7-
catch (Exception e)
8-
{
6+
7+
catch (Exception e) {
98
System.out.println("He Dude, you can't make an int out off that. Stop trying to make it happens");
109
}
11-
finally
12-
{
10+
11+
finally {
1312
System.out.println("Always executed in the finally block");
1413
}
14+
1515
System.out.println("End Here");
1616
}
1717
}

0 commit comments

Comments
 (0)