Domanda

I'm having a hard time figuring out how to throw and catch exceptions.
I Think I have the general syntax right, at least according to the book that I'm using, but I keep getting errors.

Can anyone help me out with the syntax?

public Movie( String title, int yearReleased, double rating){
    try{
        if (rating < 4.1 && rating >= 0.0)
            this.rating = rating; 
        else
            throw new IllegalArgumentException;
    catch (IllegalArgumentException e){
        System.out.println("This rating is invalid");
    }
}
È stato utile?

Soluzione

You have two issues:

1) Your closing } for the try is inside the if.

2) You are not properly calling the constructor of IllegalArgumentException. Do `throw new IllegalArgumentException();

In the future, you should read and try to understand the compiler message. It is most likely telling you exactly what there errors are and where. (That is why your question has been down-voted so much.)

I get that you're new to this so I am more than happy to help you out.

Happy coding.

Altri suggerimenti

The mistakes we're doing while not enclosing brackets..

You have a redundant closing brackets.

this.rating = rating; }

Please remove it.

try

throw new ArgumentException();

because it is constructor and you forgot to put parentheses

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top