2

I have a mini-project and a lot of classes. I created an exception for a field, it doesn't work

public C(..., int yearX, ...) throws InitException {
        if (year == 2000) {
            ...
            year = yearX;
            ...
        } else
            throw new InitAnneeEC();
    }
3
  • Might be a little easier if it's in English . . but you also should make the code smaller, i.e narrow down where the issue is Commented Mar 13, 2013 at 2:17
  • I think you don't understand the purpose of exceptions. If you throw an exception in a method or constructor, that method or constructor exits immediately. If it's a constructor, the object construction fails, and it's as if the object was never created. It sounds to me like that's what you're complaining about -- but actually, that's exactly how it's supposed to work, and in fact, that's the only reason to ever throw an exception from a constructor: if you want to cancel creation of the object. Commented Mar 13, 2013 at 2:18
  • When an exception is thrown from the constructor of an object, it's expected that it will not be initialised. What do you want to happen? Commented Mar 13, 2013 at 2:20

1 Answer 1

2

Your problem is in your constructor you compare year but you don't set it's value first, so the exception always happen.

    public C(..., int yearX, ...) throws InitException {
        if (year == 2000) {
            ...
            year = yearX;
            ...
        } else
            throw new InitAnneeEC();
    }

When you doing if (year == 2000) actually it's used the default value: 0, so the comparison always false. I guess you want to set anneeEC value with anneeE value.

Try to change your code like this:

    public C(..., int yearX, ...) throws InitException {
        year = yearX;
        if (year == 2008) {
            ...
        } else
            throw new InitException();
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.