PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Java try-catch Block

← All stacks

Theory

90/270

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.

Diagram
try { 10 / 0 }
        │
        ▼
  catch ArithmeticException
        │
        ▼
  print message
Exam tip

Write try { 10/0 } catch (ArithmeticException e) and say you print the message — never empty catch.

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.

Short notes

  • Deftry = risky code. catch = backup if that error happens.
  • RuleSpecific catch first, then broader. Don’t swallow the error.
  • RememberIf no exception, catch is skipped.
  • TrapEmpty catch { } hides the real bug.

Questions

1

What goes in try?

2

What goes in catch?

3

Why not empty catch?

Previous← Exception Handling in JavaNextMultiple Catch Block in Java →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.