R
Rishtaara
Java Fundamentals
Lesson 24 of 36Article17 min

Errors, Debugging & Exceptions

Compile errors — typos, wrong types — javac catches before run. Fix syntax and types.

Errors — compile time vs runtime

Compile errors — typos, wrong types — javac catches before run. Fix syntax and types.

Runtime errors — crash while running: divide by zero, null pointer, array out of bounds.

Real-life example: Compile error = wrong address on envelope before posting. Runtime error = letter returned after delivery attempt fails.

  • Syntax error — missing semicolon, brace
  • Logic error — program runs but wrong answer
  • Exception — runtime problem with stack trace

Debugging — finding bugs

Read error messages — line number and exception type. Use System.out.println to trace values.

IDE debuggers let you pause, step line by line, and inspect variables.

Real-life example: Debugging is detective work — follow clues (logs) from crime scene (crash line) to culprit (bug).

Debug with println
int total = 0;
for (int i = 0; i < 5; i++) {
    total += i;
    System.out.println("i=" + i + " total=" + total);
}

Exceptions — try, catch, finally

try { risky code } catch (Exception e) { handle } finally { always runs }.

Checked exceptions must be handled or declared. Unchecked extend RuntimeException.

Real-life example: try is attempting payment. catch is "card declined — show message." finally is "close checkout screen either way."

try-catch-finally
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
} finally {
    System.out.println("Cleanup done");
}