Warm‑up: Checked vs Unchecked + finally + try-with-resources (with answer)
CheckedUncheckedfinallytry-with-resourcesWarm-up
Warm‑up:
You read a file and parse an integer.
Print 4 lines:
1) Checked exception examples
2) Unchecked exception examples
3) finally usage (cleanup)
4) try-with-resources usage (auto close)
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
import java.io.*; // IO exceptions
public class Main {
// ✅ TODO: Student must implement only this method
static void explainBasics() {
// TODO:
// - Print 4 lines as described (checked/unchecked/finally/try-with-resources)
throw new UnsupportedOperationException("TODO");
}
public static void main(String[] args) {
explainBasics(); // run warm-up
}
}
Answer (Logic + Code)
Checked: IOException/FileNotFoundException (must catch or declare).
Unchecked: NumberFormatException/NullPointerException (Runtime).
finally: cleanup guaranteed.
try-with-resources: preferred for AutoCloseable resources like readers/streams.
System.out.println("Checked: IOException, FileNotFoundException (catch/throws required).");
System.out.println("Unchecked: NullPointerException, NumberFormatException (runtime).");
System.out.println("finally: cleanup that must run even if exception happens.");
System.out.println("try-with-resources: auto-close AutoCloseable (preferred).");
Scenario:
Input for quantity may include spaces/quotes/unicode/special chars.
Rules: trim, remove quotes, remove ✅, parse int.
If invalid => return defaultValue and print friendly message.
Implement ONLY: Parser.safeInt(raw, defaultValue).
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
class Parser {
// ✅ TODO: Student must implement only this method
static int safeInt(String raw, int defaultValue) {
// TODO: normalize + try parse + catch NumberFormatException
throw new UnsupportedOperationException("TODO");
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Parser.safeInt(" \"12x\" ✅ !@# ", 5));
}
}
Answer (Logic + Code)
Use try/catch for parsing; return default to keep caller safe; log why fallback happened.
static int safeInt(String raw, int defaultValue) {
String s = (raw == null ? "" : raw.trim());
s = s.replace(""", "").replace("✅", "").trim();
try { return Integer.parseInt(s); }
catch (NumberFormatException ex) {
System.out.println("Invalid integer: '" + raw + "' => default=" + defaultValue);
return defaultValue;
}
}
Scenario:
Validate order arguments:
- customerId not blank
- amount > 0
- currency is 3 letters (INR/USD...)
Implement ONLY: OrderValidator.validate(...).
Throw IllegalArgumentException with clear message.
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
class OrderValidator {
// ✅ TODO: Student must implement only this method
static void validate(String customerId, int amount, String currency) {
// TODO: guard clauses and throw IllegalArgumentException
throw new UnsupportedOperationException("TODO");
}
}
public class Main {
public static void main(String[] args) {
OrderValidator.validate(" ", -10, "inr✅");
}
}
Answer (Logic + Code)
Use IllegalArgumentException for bad inputs; validate early; keep messages actionable.
static void validate(String customerId, int amount, String currency) {
String cid = (customerId == null ? "" : customerId.trim());
String cur = (currency == null ? "" : currency.replace("✅","").trim().toUpperCase());
if (cid.isEmpty()) throw new IllegalArgumentException("customerId must not be blank");
if (amount <= 0) throw new IllegalArgumentException("amount must be > 0");
if (cur.length() != 3) throw new IllegalArgumentException("currency must be 3 letters: " + currency);
}
3
Audit Trail — Ensure cleanup in finally
finallyCleanupRobustnessModerate
Scenario:
Audit session must always close even on failure.
Implement ONLY: AuditService.process(input).
- open()
- if input contains FAIL => throw RuntimeException
- finally => close() always
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
class AuditService {
void open(){ System.out.println("AUDIT OPEN"); }
void close(){ System.out.println("AUDIT CLOSE"); }
// ✅ TODO: Student must implement only this method
void process(String input) {
// TODO: try/finally with close()
throw new UnsupportedOperationException("TODO");
}
}
public class Main {
public static void main(String[] args) {
new AuditService().process("PAYMENT FAIL ✅ α/β !@#");
}
}
Answer (Logic + Code)
finally guarantees cleanup; essential for resources/transactions/audit sessions.
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
class InvalidCredentialsException extends Exception {
// ✅ TODO: Student must implement only this constructor
InvalidCredentialsException(String message) {
// TODO: call super(message)
throw new UnsupportedOperationException("TODO");
}
}
class LoginService {
// ✅ TODO: Student must implement only this method
static void login(String user, String pass) throws InvalidCredentialsException {
// TODO: normalize and validate; else throw InvalidCredentialsException
throw new UnsupportedOperationException("TODO");
}
}
public class Main {
public static void main(String[] args) {
try {
LoginService.login(" gopi ✅ ", " wrong\"pass\" !@# ");
System.out.println("Login success");
} catch (InvalidCredentialsException ex) {
System.out.println("Login failed: " + ex.getMessage());
}
}
}
Answer (Logic + Code)
Checked custom exceptions represent business errors; caller handles them explicitly.
InvalidCredentialsException(String message){ super(message); }
static void login(String user, String pass) throws InvalidCredentialsException {
String u = (user==null?"":user.replace("✅","").trim()).toLowerCase();
String p = (pass==null?"":pass.replace("✅","").trim()).replace(""","");
if (!u.equals("gopi") || !p.equals("itq@123")) throw new InvalidCredentialsException("Invalid username/password");
}
6
Service Wrapper — Translate IOException to Runtime ApiException
WrappingCauseIOExceptionComplex
Scenario:
Low-level readFile throws IOException.
Your service must catch IOException and throw ApiException (Runtime) with cause preserved.
Implement ONLY:
- ApiException(message,cause) constructor
- FileService.safeRead(path)
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
import java.io.*;
class ApiException extends RuntimeException {
// ✅ TODO: Student must implement only this constructor
ApiException(String message, Throwable cause) {
// TODO: call super(message, cause)
throw new UnsupportedOperationException("TODO");
}
}
class FileService {
static String readFile(String path) throws IOException {
if (path.toLowerCase().contains("missing")) throw new FileNotFoundException("File not found: " + path);
return "OK:" + path;
}
// ✅ TODO: Student must implement only this method
static String safeRead(String path) {
// TODO: normalize; try readFile; catch IOException -> throw ApiException
throw new UnsupportedOperationException("TODO");
}
}
public class Main {
public static void main(String[] args) {
System.out.println(FileService.safeRead(" C:/data/missing-α.txt ✅ !@# "));
}
}
Answer (Logic + Code)
Exception translation keeps API clean; preserve cause for debugging.
Payment Parser — Multi-catch and Rethrow with Context
multi-catchrethrowContextComplex
Scenario:
Parse: PAY amount=<int> currency=<3 letters>
Input may contain quotes, unicode, special chars.
Implement ONLY: PaymentCommand.parse(input)
Use multi-catch for parsing problems; rethrow IllegalArgumentException with cause.
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
class PaymentCommand {
final int amount; final String currency;
PaymentCommand(int amount, String currency){ this.amount=amount; this.currency=currency; }
// ✅ TODO: Student must implement only this method
static PaymentCommand parse(String input) {
// TODO: normalize; extract amount/currency; multi-catch; rethrow with context
throw new UnsupportedOperationException("TODO");
}
public String toString(){ return amount + " " + currency; }
}
public class Main {
public static void main(String[] args) {
System.out.println(PaymentCommand.parse(" PAY amount=\"12x\" currency=INR ✅ α/β !@# "));
}
}
Answer (Logic + Code)
Multi-catch reduces duplication; rethrow with improved message helps debugging.
static PaymentCommand parse(String input) {
String s=(input==null?"":input.trim()).replace("✅","").replace(""","").trim();
try {
int aIdx=s.indexOf("amount="), cIdx=s.indexOf("currency=");
String aStr=s.substring(aIdx+7).trim().split("\s+")[0];
String cStr=s.substring(cIdx+9).trim().split("\s+")[0];
int amount=Integer.parseInt(aStr);
String cur=cStr.trim().toUpperCase();
if (cur.length()!=3) throw new IllegalArgumentException("currency invalid");
return new PaymentCommand(amount, cur);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException ex) {
throw new IllegalArgumentException("Invalid payment command: "+input+" | cause="+ex.getMessage(), ex);
}
}
8
Resource Tracker — AutoCloseable + Suppressed
AutoCloseableSuppressedtry-with-resourcesComplex
Scenario:
Custom resource may fail on close().
Use try-with-resources. If body throws and close throws => close exception becomes suppressed.
Implement ONLY:
- TrackedResource.close()
- Demo.run(failInBody, failInClose)
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
class TrackedResource implements AutoCloseable {
private final String name; private final boolean failOnClose;
TrackedResource(String name, boolean failOnClose){ this.name=name; this.failOnClose=failOnClose; }
// ✅ TODO: Student must implement only this method
public void close() throws Exception {
// TODO: print CLOSING; optionally throw close exception
throw new UnsupportedOperationException("TODO");
}
}
class Demo {
// ✅ TODO: Student must implement only this method
static void run(boolean failInBody, boolean failInClose) {
// TODO: try-with-resources + catch Exception; print suppressed count
throw new UnsupportedOperationException("TODO");
}
}
public class Main {
public static void main(String[] args) {
Demo.run(true, true);
}
}
Answer (Logic + Code)
try-with-resources ensures close() runs; suppressed exceptions are attached to primary failure.
public void close() throws Exception {
System.out.println("CLOSING " + name);
if (failOnClose) throw new Exception("CLOSE_FAIL:" + name);
}
static void run(boolean failInBody, boolean failInClose) {
try (TrackedResource r = new TrackedResource("R-α/β ✅", failInClose)) {
if (failInBody) throw new RuntimeException("BODY_FAIL");
System.out.println("BODY_OK");
} catch (Exception ex) {
System.out.println("PRIMARY: " + ex.getMessage());
System.out.println("SUPPRESSED_COUNT: " + ex.getSuppressed().length);
}
}
9
Retry Utility — Retry only IOException with Backoff
RetryBackoffIOExceptionComplex
Scenario:
Call flaky action that may throw IOException.
Retry:
- attempts=3
- backoff 100ms, 200ms
- retry only IOException; other exceptions => fail fast
Implement ONLY: Retry.callWithRetry(action)
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
import java.io.*;
@FunctionalInterface
interface ThrowingSupplier<T>{ T get() throws Exception; }
class Retry {
// ✅ TODO: Student must implement only this method
static String callWithRetry(ThrowingSupplier<String> action) {
// TODO: retry loop with backoff; only IOException is retryable
throw new UnsupportedOperationException("TODO");
}
}
public class Main {
static int attempt=0;
public static void main(String[] args) {
String result = Retry.callWithRetry(() -> {
attempt++;
if (attempt==1) throw new IOException("net down ✅");
if (attempt==2) throw new IOException("timeout α/β");
return "OK ✅";
});
System.out.println(result);
}
}
Answer (Logic + Code)
Retry expected transient failures; include backoff; surface last error after max attempts.
Scenario:
Import product lines: id,name,price
Collect all row errors and throw one BulkImportException at end.
Implement ONLY:
- BulkImportException constructor (sets message + stores errors)
- BulkImporter.importLines(lines)
✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Exceptions scenario (students implement ONLY // ✅ TODO)Ctrl+C
import java.util.*;
class BulkImportException extends Exception {
final List<String> errors;
// ✅ TODO: Student must implement only this constructor
BulkImportException(List<String> errors) {
// TODO: call super("Bulk import failed with X errors"); assign errors
throw new UnsupportedOperationException("TODO");
}
}
class Product {
final String id,name; final int price;
Product(String id,String name,int price){ this.id=id; this.name=name; this.price=price; }
public String toString(){ return id+":"+name+":"+price; }
}
class BulkImporter {
// ✅ TODO: Student must implement only this method
static List<Product> importLines(List<String> lines) throws BulkImportException {
// TODO: validate each row; collect "Row i: ..." errors; throw once
throw new UnsupportedOperationException("TODO");
}
}
public class Main {
public static void main(String[] args) {
List<String> lines = Arrays.asList(
"P-α1,Phone,1000 ✅",
" ,Laptop,2000",
"P-γ3, ,0 !@#",
"P-δ4,Tablet,12x"
);
try {
List<Product> p = BulkImporter.importLines(lines);
System.out.println("Imported=" + p.size());
System.out.println(p);
} catch (BulkImportException ex) {
System.out.println(ex.getMessage());
// In real use: print ex.errors line by line
}
}
}
Answer (Logic + Code)
Bulk validation improves UX; report all row errors together instead of failing fast.
BulkImportException(List<String> errors) {
super("Bulk import failed with " + (errors==null?0:errors.size()) + " errors");
this.errors = (errors==null? new ArrayList<>() : errors);
}
static List<Product> importLines(List<String> lines) throws BulkImportException {
List<String> errors = new ArrayList<>();
List<Product> out = new ArrayList<>();
if (lines == null) return out;
for(int i=0;i<lines.size();i++){
String s = (lines.get(i)==null?"":lines.get(i)).replace("✅","").trim();
String[] p = s.split(",", -1);
if(p.length<3){ errors.add("Row "+(i+1)+": expected 3 columns"); continue; }
String id=p[0].trim(), name=p[1].trim(), priceStr=p[2].trim();
boolean rowOk=true;
if(id.isEmpty()){ errors.add("Row "+(i+1)+": id blank"); rowOk=false; }
if(name.isEmpty()){ errors.add("Row "+(i+1)+": name blank"); rowOk=false; }
int price=-1;
try { price=Integer.parseInt(priceStr); }
catch(NumberFormatException ex){ errors.add("Row "+(i+1)+": price not int"); rowOk=false; }
if(price<=0){ errors.add("Row "+(i+1)+": price must be > 0"); rowOk=false; }
if(rowOk) out.add(new Product(id,name,price));
}
if(!errors.isEmpty()) throw new BulkImportException(errors);
return out;
}