0

I'm trying to create a method f1(x) that throws an exception when x equals 5. After that I will try to call that method from another method f2() to invoke that exception. Then I have to have f2() recover by calling f1(x+1). I tried coding something, but I'm stuck. Here is the 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 is 5");
    }

}


public static void main(String[] args) {
    FiveException x5 = new FiveException();
    x5.f2();
}

}

The print statement works, but I'm not sure how to call f(x+1). Any help on how to fix this and any techniques to write exceptions is appreciated.

3
  • Your code that throws the exception should not be in the FiveException class. Commented May 14, 2013 at 23:42
  • Where do you want to call f1(x + 1)? Inside which method? Commented May 14, 2013 at 23:44
  • @fhelwanger I tried calling f1(x + 1) under the catch statement in f2() but it was giving me an error. Commented May 14, 2013 at 23:52

1 Answer 1

1

Because f1 throws FiveException, wherever you call f1 you must either catch the exception or throw it to the method calling the method that raises the exception. For 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 your code is confusing... normally, it isn't the exception class that throws itself, you have other classes that throw the exception class.

If it's being invoked inside a catch statement, you must surround it with another try-catch, 'cause the code inside catch isn't protected, like this:

public void f2() {
    int x = 5;
    try {
        f1(x);
    }catch (FiveException e) {
       System.out.println("x is 5");
       try {
           f1(x + 1);
       } catch (FiveException e) {
           e.printStackTrace();
       }
    }
}

But this code is ugly, you can write the 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 is 5");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting. I will study this and will see if this is the desired code I'm looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.