Exception Handling & try-with-resources
Exception Handling — checked vs unchecked, try/catch/finally, এবং আধুনিক try-with-resources
1. What Is an Exception?
An exception is Java's way to say "I can't continue normally." When thrown, it unwinds
the call stack until someone catches it, or until the program ends. Java distinguishes
checked exceptions (the compiler forces you to handle or declare them) from unchecked
ones (subclasses of RuntimeException) which typically indicate bugs.
RuntimeException-এর subclass) সাধারণত বাগ নির্দেশ করে।
2. try / catch / finally
Wrap code that might throw in try; catch specific types in catch;
put cleanup that must always run in finally.
try-তে রাখুন; নির্দিষ্ট type ধরতে catch ব্লক; সব সময় চালানোর জন্য cleanup finally-তে।
class Main {
public static void main(String[] args) {
int[] xs = { 10, 20, 30 };
try {
System.out.println(xs[5]); // out of bounds
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("bad index: " + ex.getMessage());
} catch (RuntimeException ex) {
System.out.println("other runtime problem: " + ex);
} finally {
System.out.println("cleanup always runs");
}
// Multi-catch
try {
Integer.parseInt("not-a-number");
} catch (NumberFormatException | ArithmeticException ex) {
System.out.println("parse/math error: " + ex.getClass().getSimpleName());
}
}
}
3. Checked vs Unchecked
| Aspect | Checked | Unchecked | বাংলায় |
|---|---|---|---|
| Parent | Exception | RuntimeException | Parent class আলাদা। |
| Compiler force | Must catch or declare | No | Checked-এ compiler জোরে। |
| Typical cause | External failure (I/O, network) | Programming bugs | বাহ্যিক ব্যর্থতা বনাম বাগ। |
| Examples | IOException, SQLException | NullPointerException, IllegalArgumentException | দৃষ্টান্ত। |
catch (Exception e) {}).
নিয়ম: recoverable, expected ব্যর্থতায় checked; programming bug-এ unchecked।
catch (Exception e) {} — কখনোই নয়।
4. try-with-resources (Java 7+)
Any resource that implements AutoCloseable can be declared in the try(...)
header and will be closed automatically — even if an exception is thrown. This replaces noisy
try/finally cleanup code.
AutoCloseable implement করে, তাকে try(...)-এর header-এ declare করলে Java নিজেই close করে — exception হলেও। এটি try/finally-র বিশৃঙ্খলা দূর করে।
class Main {
// Any AutoCloseable works — here a tiny in-memory resource for demo
static class Scoped implements AutoCloseable {
String name;
Scoped(String n) { name = n; System.out.println("open " + n); }
public void doWork() { System.out.println("work " + name); }
@Override public void close() { System.out.println("close " + name); }
}
public static void main(String[] args) {
// Resources close in reverse order at end of block — even on exception
try (Scoped a = new Scoped("A");
Scoped b = new Scoped("B")) {
a.doWork();
b.doWork();
if (args.length == 42) throw new RuntimeException("boom");
}
System.out.println("after block");
}
}
5. Custom Exception Classes
Define domain-specific exception types by extending RuntimeException (for unchecked) or
Exception (for checked). Always preserve the original cause via the Throwable
constructor — losing the cause is a common production-debugging trap.
RuntimeException (unchecked) বা Exception (checked) extend করুন। মূল cause-কে Throwable-constructor-এ pass করে রাখুন — production debug-এ cause হারিয়ে ফেলা সবচেয়ে বড় ফাঁদ।
class Main {
static class InsufficientFundsException extends RuntimeException {
final long shortfall;
InsufficientFundsException(long shortfall, Throwable cause) {
super("short by " + shortfall + " tk", cause);
this.shortfall = shortfall;
}
}
static void debit(long balance, long amount) {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance, null);
}
System.out.println("debited " + amount + ", remaining " + (balance - amount));
}
public static void main(String[] args) {
try {
debit(1000, 500);
debit(1000, 1500);
} catch (InsufficientFundsException ex) {
System.out.println("caught: " + ex.getMessage());
}
}
}
6. Vocabulary
| Term | Meaning | বাংলায় |
|---|---|---|
throw | Actively raise an exception. | exception ছোঁড়ার keyword। |
throws | Method declares possible checked exceptions. | Method declaration-এ possible checked exception। |
finally | Runs whether or not an exception was thrown. | exception যাই হোক, সব সময় চলে। |
AutoCloseable | Interface used by try-with-resources. | try-with-resources-এর interface। |
| Stack trace | Path of calls at the moment of failure. | ব্যর্থতার মুহূর্তে call chain। |
| Cause chain | Nested exception revealing the root cause. | মূল কারণ খুঁজে পাওয়ার exception চেইন। |
7. Practice Problems
-
Catch a
NumberFormatExceptionwhen parsing"abc"and print a friendly message."abc"parse করতে গিয়েNumberFormatExceptionধরে একটি বন্ধুত্বপূর্ণ message দিন।✨ Show Answer
Main.javaclass Main { public static void main(String[] args) { try { int n = Integer.parseInt("abc"); System.out.println(n); } catch (NumberFormatException ex) { System.out.println("Please enter a valid number."); } } } -
Write a custom unchecked exception
AgeInvalidExceptionand throw it when age is negative.নিজেAgeInvalidExceptionতৈরি করুন; age নেগেটিভ হলে throw করুন।✨ Show Answer
Main.javaclass Main { static class AgeInvalidException extends RuntimeException { AgeInvalidException(String msg) { super(msg); } } static void setAge(int a) { if (a < 0) throw new AgeInvalidException("age cannot be negative"); System.out.println("age = " + a); } public static void main(String[] args) { setAge(22); try { setAge(-3); } catch (AgeInvalidException ex) { System.out.println("caught: " + ex.getMessage()); } } } -
Demonstrate
try-with-resourceswith twoAutoCloseableresources — show they close in reverse order.দুটিAutoCloseableresource দিয়েtry-with-resourcesদেখান; reverse order-এ close হয় এটা প্রমাণ করুন।✨ Show Answer
Main.javaclass Main { static class R implements AutoCloseable { String n; R(String n) { this.n = n; System.out.println("open " + n); } @Override public void close() { System.out.println("close " + n); } } public static void main(String[] args) { try (R a = new R("A"); R b = new R("B")) { System.out.println("inside block"); } } } -
Explain when to use
finallyversus try-with-resources.finallyকবে, try-with-resources কবে — পার্থক্য ব্যাখ্যা করুন।✨ Show Answer
Answer: Use
try-with-resourceswhenever the resource implementsAutoCloseable— files, sockets, DB connections, streams. It is shorter, exception-safe, and automatically suppresses exceptions fromclose()without losing the primary exception. Keepfinallyonly for cleanup that is not a closable resource — e.g., restoring a ThreadLocal, logging a metric, or releasing a manual lock that doesn't implementAutoCloseable.Resource যদি
AutoCloseableহয় (file, socket, DB connection, stream) — সব সময়try-with-resources। এটি ছোট, exception-safe,close()-এর exception-কে suppress করে মূল exception সংরক্ষণ করে।finallyরাখুন শুধু সেই cleanup-এর জন্য যা resource নয় — যেমন ThreadLocal reset, metric log, বা manual lock release যেটিAutoCloseableনয়। -
Wrap a lower-level
IOExceptioninto a domainReportFailedExceptionpreserving the cause.নিচু স্তরেরIOException-কে domain-levelReportFailedException-এ wrap করুন; cause হারাবেন না।✨ Show Answer
Main.javaimport java.io.*; class Main { static class ReportFailedException extends RuntimeException { ReportFailedException(String m, Throwable cause) { super(m, cause); } } static void buildReport() { try { throw new IOException("disk full"); } catch (IOException ex) { throw new ReportFailedException("could not write daily report", ex); } } public static void main(String[] args) { try { buildReport(); } catch (ReportFailedException ex) { System.out.println("top level: " + ex.getMessage()); System.out.println("root cause: " + ex.getCause()); } } }
Summary — Module 31
Java separates checked exceptions (must be declared or handled) from unchecked
(RuntimeException). Use try/catch/finally for general flow, but prefer
try-with-resources for anything that implements AutoCloseable — it closes
resources in reverse order even when an exception is thrown. Build domain-specific exception types and
always preserve the cause when wrapping.
RuntimeException) সাধারণত বাগ বোঝায়। try/catch/finally আছে, কিন্তু AutoCloseable resource-এ সব সময় try-with-resources — exception হলেও reverse order-এ close হয়। নিজের domain exception class বানান, এবং wrap-এর সময় মূল cause সব সময় pass করুন।