First Part Design and implement a program that creates an exception class called
ID: 3536122 • Letter: F
Question
First Part
Design and implement a program that creates an exception class
called InvalidDocumentCodeException, designed to be thrown
when an improper designation for a document is encountered
during processing. Suppose in a particular business all documents
are given a two-character designation starting with either U, C,
or P, standing for unclassified, confidential, or proprietary. If a
document designation is encountered that doesn’t fit that description,
the exception is thrown. Create a driver program to test the
exception, allowing it to terminate the program.
Second Part
Modify the solution to the above probelm such that it catches and handles
the exception if it is thrown. Handle the exception by printing an
appropriate message, and then continue processing.
Only need the second part to be done.
Explanation / Answer
public class InvalidDocumentCodeException extends Exception{
public InvalidDocumentCodeException(){
}
public String getMessage(){
return "Document code must be U (Unclassified), C (Confidential), or P (Proptietary)." +
" Document will default to Unclassified.";
}
}
public class Document {
private String dType = "U";
public Document(String docType){
try{
if( docType.compareToIgnoreCase("U") != 0
&& docType.compareToIgnoreCase("C") != 0
&& docType.compareToIgnoreCase("P") != 0 )
throw new InvalidDocumentCodeException();
dType = docType;
}
catch(InvalidDocumentCodeException e){
System.out.println("Exception caught and handled! Continuing...");
System.out.println(e.getMessage());
}
}
public void setDocType(String docType){
dType = docType;
}
public String toString(){
return "Document type: "+ dType.toUpperCase();
}
}
import java.util.Scanner;
public class Starter {
public static void main(String[] args) {
String done = "DONE";
System.out.println("DocType? U = Unclassified, C = Confidential, P = Proprietary.");
System.out.println("Type DONE, in all caps to end.");
Scanner scan = new Scanner(System.in);
String docType = scan.next();
while(docType.compareTo(done) != 0){
Document doc = new Document(docType);
System.out.println(doc);
docType = scan.next();
}
System.out.println("Program Fin~");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.