Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to throw an exception if the object that is being added has a duplicate

Tags:

java

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.

like image 893
Wahegurupal Singh Avatar asked Feb 23 '16 01:02

Wahegurupal Singh


2 Answers

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 newoperator. For example, throw new MyCustomeException().

like image 194
josivan Avatar answered Oct 31 '22 16:10

josivan


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/

like image 36
Sriniketh Avatar answered Oct 31 '22 17:10

Sriniketh