Java try-catch Block
try holds risky code — divide, parse Integer, open a file. catch is the backup if that problem happens. Without try-catch, 10 / 0 kills the whole program. With try-catch, you print a message and the rest of main can still run. That is the point: don’t crash blindly.
Let’s take this on the board. try { int x = 10 / 0; System.out.println(x); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); }. 10 / 0 throws. The println(x) never runs. catch runs. Output: Cannot divide by zero. Now change 0 to 2. No exception. try finishes, prints 5, catch is skipped. Dry-run both numbers before you compile.
You can write more than one catch. Put specific types first: ArithmeticException before Exception. If you catch Exception first, the specific catch below becomes dead code. Empty catch { } is the worst habit in class — the bug hides and you think the program is fine. Always print e.getMessage() or log it.
If nothing is thrown, catch is skipped. finally (if you add it) still runs for cleanup — close file, close connection. Learn try-catch first, then finally, then throw/throws. Don’t mix all five keywords on day one.
try { 10 / 0 }
│
▼
catch ArithmeticException
│
▼
print messageWrite try { 10/0 } catch (ArithmeticException e) and say you print the message — never empty catch.