Custom Exceptions and try with resources
Create your own exception by extending Exception (checked) or RuntimeException (unchecked). try with resources closes AutoCloseable objects automatically.
Example
public class Main {
static class LowBalance extends Exception { LowBalance(String m) { super(m); } }
static class Res implements AutoCloseable { public void close() { System.out.println("closed"); } }
static void pay(int bal, int amt) throws LowBalance { if (amt > bal) throw new LowBalance("need " + (amt - bal) + " more"); }
public static void main(String[] args) {
try (Res r = new Res()) { pay(10, 25); } catch (LowBalance e) { System.out.println("caught " + e.getMessage()); } finally { System.out.println("done"); }
}
}Result
closed caught need 15 more done
Exercise
Resource block syntax.
try (Res r = new Res ) {}
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.