Nearby lessons

60 of 125

Java - try and catch

📌 What You Will Learn
  • What an exception is and why programs crash
  • The try, catch, finally structure
  • Checked vs unchecked exceptions (with the updated rule)
  • throw vs throws
  • Creating your own (custom) exceptions
  • try-with-resources — the modern way

try and catch is a core concept of the Java language. This lesson explains The try-catch-finally Structure with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The try-catch-finally Structure

Example01
JCode Cell
1try {
2 // risky code that may throw an exception
3} catch (ExceptionType e) {
4 // code to handle that exception
5} finally {
6 // always runs: with or without exception
7}

The try-catch-finally Structure

In simple words: `try` watches the risky code, `catch` handles the error, and `finally` always runs — with or without an exception. Once an exception is thrown, the rest of the try block is skipped and control jumps to the matching catch.
Example02
JCode Cell
1class TryCatchDemo {
2 public static void main(String[] args) {
3 try {
4 int a = 10, b = 0;
5 System.out.println(a / b);
6 System.out.println("This line will not run");
7 } catch (ArithmeticException e) {
8 System.out.println("Cannot divide by zero!");
9 } finally {
10 System.out.println("finally always runs");
11 }
12 System.out.println("Program continues normally");
13 }
14}
Output
Cannot divide by zero! finally always runs Program continues normally
📝 Key Takeaways
  • Exception = a run-time problem that stops the program; handling prevents the crash.
  • try keeps risky code, catch handles the problem, finally always runs.
  • Checked exceptions must be handled; unchecked (RuntimeException) are optional to handle.
  • throw throws an exception; throws warns that a method may throw one.
  • Custom exceptions extend Exception or RuntimeException for business rules.
  • try-with-resources (Java 7+) closes files/connections automatically.
  • Errors (like OutOfMemoryError) are system problems — not meant to be caught.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1