This is my code:

public boolean SetYear (String year)
{
		if (year.matches("[0-9]{4}"))
		{ 
		_year=year;
		return true;
                }
    return false;
}

Instead of return false I want to make a runtime error with my massage. Something like "the value must be 4 digits"
How can I do it?

Specifically, you probably want to throw an IllegalArgumentException. You can set whatever message you want in the constructor.

commented: The best option +7

Or if you want to generate any old runtime error, I've learned plenty of ways to do that in my time programming. :)

One of the most common is indexing an array by an index too low or too high

Define your own exception handler and use try/catch

Define your own exception handler and use try/catch

Most probably you mean define his own (custom) exception class, but this would be just an overkill.
Ezzaral's suggestion of throwing an IllegalArgumentException for me hits the nail on the head.

He wants a custom error message so it seems like a better idea

<Ignore>

He wants a custom error message so it seems like a better idea

You can set the "message" for most (if not all) inbuilt exceptions including the IllegalArgumentException (for whom this constructor can be used which was also mentioned by Ezzaral in his second post).

Yes, generally you only need to create a custom exception if you are wanting to pass along additional information that wouldn't be possible with one of the standard exceptions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.