我正在尝试编写由三个类组成的程序,每个类都有一个例外-使用继承。在我们的测试人员类中,我们假设使用catch块,但是我很难理解这个想法。
程序结果如下:
使用catch块捕获所有EndOfSentenceException,导致程序打印消息并终止。
public class EndOfSentenceException extends Exception
{
public EndOfSentenceException(String str)
{
super("The sentence ends correctly.");
}
}
public class PunctuationException extends EndOfSentenceException
{
public PunctuationException(String str)
{
super("The sentence does not end correctly.");
}
}
public class CommaException extends PunctuationException
{
public CommaException(String str)
{
super("You can't end a sentence in a comma.");
}
}
public class Driver
{
public static void checkSentence(String str)
throws EndOfSentenceException
{
if(!(str.endsWith(".") || str.endsWith("!") || str.endsWith("?")))
{
throw new PunctuationException(str);
}
if(str.endsWith(","))
{
throw new CommaException(str);
}
}
public static void main(String[] args)
throws EndOfSentenceException
{
//Initialize a scanner to take user input
Scanner scan = new Scanner(System.in);
String input = "";
//Ask the user to input their sentence and assign it to input
System.out.println("\nEnter a sentence:");
input = scan.nextLine();
try
{
checkSentence(input);
System.out.println("The Sentence ends correctly.");
}
catch(PunctuationException error)
{
System.out.println(error.getMessage());
}
catch(CommaException error)
{
System.out.println(error.getMessage());
}
scan.close();
}
}
答案 0 :(得分:0)
java中的异常应该扩展Throwable
(通常是Exception
或RuntimeException
)。因此,您的自定义异常可能如下所示:
public class PunctuationException extends Exception {
public PunctuationException() {
super("The sentence does not end correctly");
}
public PunctuationException(String message) {
super(message);
}
}
public class CommaException extends PunctuationException {
public CommaException() {
super("You can't end a sentence in a comma.");
}
}
第二,异常本身不应对检查条件负责。此检查不应例外。
class Driver {
public static void main(String... args) {
try {
checkSentence("....");
System.out.println("The sentence ends correctly.");
} catch(PunctuationException e) {
System.out.println(e.getMessage());
}
}
public static void checkSentence(String str) throws PunctuationException {
str = str != null ? str.trim() : null;
if (str == null)
return;
if (!str.endsWith(".") && !str.endsWith("!") && !str.endsWith("?"))
throw new PunctuationException();
if (str.endsWith(","))
throw new CommaException();
}
}
答案 1 :(得分:0)
我同意oleg.cherednik。
也许,在像他提到的那样创建自定义异常类之后,您可以像下面那样使测试器类成为
public class TesterClass{
public void checkSentenceForException() {
try {
checkInputForEnding(input); //this function will throw the particular user-defined exception
System.out.println("The sentence ends correctly.");
}
catch(PunctuationException e) {
//Desired exception output
}
catch(CommaException e) {
//Desired exception output
}
finally {
//if any cleanup is required
}
}
}
如果可以做得更好,请分享。