Java try-catch Block — Java Technical Interview Questions & Answers
Java try-catch Block
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 messageTechnical Interview Tip: Write try { 10/0 } catch (ArithmeticException e) and say you print the message — never empty catch.
Code Examples for Java try-catch Block
Example
// try-catch demo
public class Main {
public static void main(String[] args) {
try {
int x = 10 / 0;
System.out.println(x);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}Java try-catch Block — output: Cannot divide by zero. 10/0 throws ArithmeticException; catch prints the message. x is never printed.
How to Explain Java try-catch Block to an Interviewer
What goes in try?
Risky code
What goes in catch?
Backup when that error happens
Why not empty catch?
Hides the bug