I have to add a new object to an array but throw an exception if that object already exists.I don't know what to add after 'throw___________;'. I have made the object class and also a class to hold an array of that object.I have also done the part where i have to add it to the array but i don't know what exception to throw if the object already exists in that array.
The straightforward to do is throw an existent exception. You can do something like.
throw new IllegalArgumentException();
Or use the constructor with String parameter
throw new IllegalArgumentException("The value is already in the list.");
You can see the documentation of IllegalArgumentException on oracle website.
If you prefer to use a custom exception. You need to follow the suggestion of @3kings. But you have to user the new
operator. For example, throw new MyCustomeException()
.
Create a custom exception class
like the one below:
public class CustomException extends Exception
{
private static final long serialVersionUID = 1997753363232807009L;
public CustomException()
{
}
public CustomException(String message)
{
super(message);
}
public CustomException(Throwable cause)
{
super(cause);
}
public CustomException(String message, Throwable cause)
{
super(message, cause);
}
public CustomException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace)
{
super(message, cause, enableSuppression, writableStackTrace);
}
}
You can use it as follows:
throw new CustomException("blah blah blah");
Refer this link: http://examples.javacodegeeks.com/java-basics/exceptions/java-custom-exception-example/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With