954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How can I create a runtime error?

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?

stewie griffin
Light Poster
35 posts since Jul 2008
Reputation Points: 64
Solved Threads: 1
 
Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

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

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

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

BestJewSinceJC
Posting Maven
2,772 posts since Sep 2008
Reputation Points: 874
Solved Threads: 354
 

Define your own exception handler and use try/catch

jbennet
Moderator
Moderator
18,523 posts since Apr 2005
Reputation Points: 1,826
Solved Threads: 601
 
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.

stephen84s
Nearly a Posting Virtuoso
1,443 posts since Jul 2007
Reputation Points: 668
Solved Threads: 154
 

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

jbennet
Moderator
Moderator
18,523 posts since Apr 2005
Reputation Points: 1,826
Solved Threads: 601
 
stephen84s
Nearly a Posting Virtuoso
1,443 posts since Jul 2007
Reputation Points: 668
Solved Threads: 154
 
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).

stephen84s
Nearly a Posting Virtuoso
1,443 posts since Jul 2007
Reputation Points: 668
Solved Threads: 154
 

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.

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You