list of dots

User Manual    [Previous]   [Next]   

RE003 Violation of Uniqueness

Umple runtime exception thrown when uniqueness is violated in a constructor

The unique keyword in Umple can be applied to an attribute to ensure that each instance of the class in the currently running program has a unique value for that attribute. The code generated by Umple will not allow this constraint to be violated.

If an attempt is made to call the constructor of a class with an argument that would result in a violation of the uniqueness constraint, an exception will be thrown. The text of the constraint will start with the phrase "Cannot create".

In the example below,

  • s1 is first initialized with number set to 1.
  • Then an attempt is made to initialize s2 with number also set to 1. This throws the exception, but it is caught using a try-catch block.
  • Next s3 is successfully created with number 2, but an attempt is made to change the number to 1 using the method call setNumber(). This returns false, since it is only constructors that throw the exception.
  • Finally, an attempt is made to create s4, with the number set to 1. This throws the exception without a try-catch block, thus the program terminates.

Programs should be designed with logic that avoids violation of uniqueness. It is not recommended that production code relies on catching this exception as a normal part of its logic.


// This demonstrates code that will throw the
// uniqueness exception
class Student {
  unique Integer number;
  public static void main(String[] argv) {
    Student s1 = null;
    Student s2 = null;
    Student s3 = null;
    Student s4 = null;

    System.out.println("Initial\ns1= "+s1+
      "\ns2= "+s2+"\ns3= "+s3+"\n\n");

    // We set up the first student s1 with no problem
    s1 = new Student(1,"Abel");
    // For the second student we use a try catch
    // block to catch the exception
    // Ideally code would avoid creating violations
    // to start with, but the following
    // approach can be used as a safety mechanism.
    try {
      s2 = new Student(1, "Baker");
    catch (RuntimeException re) {
      System.out.println("Exception Caught: "+re+"\n");
    // We now create a student that doesn't
    // violate uniqueness
    s3 = new Student(2,"Charlie");
    // Uniqueness can also be detected by trying
    // to change a value
    // This does not throw the exception, since
    // the setNumber() method returns false
    boolean result = s3.setNumber(1);
    if(!result) System.out.println(
      "Could not change number as it would have"+
      " violated uniqueness\n");

    System.out.println("Final\ns1= "+s1+
      "\ns2= "+s2+"\ns3= "+s3+"\n\n");
    // The following will throw the exception
    // without being caught
    s4 = new Student(1, "Delta");
    // This statement will not be reached
      "This line should not be reached");


Load the above code into UmpleOnline