While writing the user defined exceptions should take care of the following aspects:
The user defined exception class should extend from Exception class.
The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.
Example
class MarksException extends Exception {
private static final long serialVersionUID = 1L;
private String ErrorMessage;
public MarksException(String ErrorMessage) {
this.ErrorMessage = ErrorMessage;
}
public String toString() {
return ErrorMessage;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Integer marks = 0;
if (args.length == 0)
throw new MarksException("Marks cannot be blank");
try {
marks = Integer.parseInt(args[0]);
} catch (Exception e) {
throw new MarksException("Marks cannot be invalid");
}
if (marks < 0) {
throw new MarksException("Marks cannot be negative");
} else {
System.out.println("Marks entered is :" + marks);
}
}
}
No comments:
Post a Comment