You may or may not have seen Exception Handling before. As part
of this course, you will learn how to use Java's exception handling mechanism
and to utilize it in your software solution to all your Cmpt 225 assignments.
This is something you will need to learn on your own as we will not be
mentioning this topic in class. More specifically, you need to learn:
class DuplicateEntryException extends ExceptionThe purpose of the method super( ), in the above constructor is to invoke the constructor of the Exception class (the superclass) and to pass it aString as a parameter. The Exception class (the superclass) has a String field member which is set to aString by its constructor (the one invoked by super( )) . This string parameter can be a description of the occurring problem (error or exception).
{
// Constructor
public DuplicateEntryException( String aString )
{
super( aString );
}
}
You would then instantiate and throw an object of class DuplicateEntryException, for example, if the user is trying to create an entry which already exists in your data collection. Here is a bit of code that illustrates this:
try
{
createEntry( "BlahBlahBlah",
... );
}
catch ( DuplicateEntryException myException
)
{
System.out.println(
myException );
}
In the createEntry( "BlahBlahBlah", ... ) method:
// this is pseudocode not Java code:
if ( "BlahBlahBlah" is found in the data
collection )
// this is syntactically
correct Java code:
throw new DuplicateEntryException(
"BlahBlahBlah already exists." );
So when the exception is caught by the above code, the line "BlahBlahBlah already exists" is printed on the screen. Of course, printing error message is not the only thing you can do when you catch an exception. One very useful thing to do would be to ask the user to create a different entry.
Notes:
C++ has a similar exception handling mechanism. Here are some links you may find useful: