java - Creating a Custom Exception -
i'm trying create method f1(x) throws exception when x equals 5. after try call method method f2() invoke exception. have have f2() recover calling f1(x+1). tried coding something, i'm stuck. here code:
public class fiveexception extends exception { public void f1(int x) throws fiveexception { if (x == 5) { throw new fiveexception(); } } public void f2() { int x = 5; try { f1(x); }catch (fiveexception e) { system.out.println("x 5"); } } public static void main(string[] args) { fiveexception x5 = new fiveexception(); x5.f2(); } } the print statement works, i'm not sure how call f(x+1). on how fix , techniques write exceptions appreciated.
because f1 throws fiveexception, wherever call f1 must either catch exception or throw method calling method raises exception. example:
public static void main(string[] args) throws fiveexception { fiveexception x5 = new fiveexception(); x5.f1(1); } or:
public static void main(string[] args) { fiveexception x5 = new fiveexception(); try { x5.f1(1); } catch (fiveexception e) { e.printstacktrace(); } } but code confusing... normally, isn't exception class throws itself, have other classes throw exception class.
if it's being invoked inside catch statement, must surround try-catch, 'cause code inside catch isn't protected, this:
public void f2() { int x = 5; try { f1(x); }catch (fiveexception e) { system.out.println("x 5"); try { f1(x + 1); } catch (fiveexception e) { e.printstacktrace(); } } } but code ugly, can write following:
public void f2() { int x = 5; fprotected(x); fprotected(x + 1); } private void fprotected(int x) { try { f1(x); }catch (fiveexception e) { system.out.println("x 5"); } }
Comments
Post a Comment