简体   繁体   English

为多个异常创建捕获块

[英]Creating a Catch Block For Multiple Exceptions

I'm trying to write this program that is made up of three classes with an exception in each class - using inheritance. 我正在尝试编写由三个类组成的程序,每个类都有一个例外-使用继承。 Inside of our tester class we are suppose to use a catch block and i'm having trouble understanding the idea. 在我们的测试人员类中,我们假设使用catch块,但是我很难理解这个想法。

The program outcome is as follows: 该计划的成果如下:

  • If the sentence ends in anything except a period (.), exclamation point (!), or question mark (?), the program should throw a PunctuationException. 如果该句子以句点(。),感叹号(!)或问号(?)以外的其他结尾,则程序应引发PunctuationException。
  • If the sentence specifically ends in a comma, the program should throw a CommaException. 如果该句子专门以逗号结尾,则程序应引发CommaException。
  • If a general PunctuationException is caught, the program should print "The sentence does not end correctly." 如果捕获到一般的PunctuationException,则程序应输出“句子未正确结束”。
  • If a CommaException is caught, the program should print "You can't end a sentence in a comma." 如果捕获到CommaException,则程序应显示“您不能以逗号结束句子”。
  • If there are no exceptions, the program should print "The sentence ends correctly." 如果没有例外,程序应打印“句子正确结束”。 and terminate. 然后终止

Use a catch block to catch all EndOfSentenceExceptions, causing the program to print a message and terminate. 使用catch块捕获所有EndOfSentenceExceptions,导致程序打印一条消息并终止。

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();
    }
}

Exceptions in java should extend Throwable (usually this is Exception or RuntimeException ). java中的异常应扩展Throwable (通常是ExceptionRuntimeException )。 Hence your custom exceptions could look like this: 因此,您的自定义异常可能如下所示:

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.");
    }
}

Second , the exception itself should not be responsible for check condition. 其次 ,异常本身不应对检查条件负责。 This check should not be in exception. 此检查不应例外。

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();
    }
}

I agree with oleg.cherednik. 我同意oleg.cherednik。

And maybe, after you have made your custom exception classes like he mentioned, you can make the tester class like follow: 也许,在像他提到的那样创建自定义异常类之后,可以使测试器类如下:

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
     }
    }
}

Do share if something better could be done. 如果可以做得更好,请分享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM