是否有另一种方法用自定义消息而不是try {} catch(Exception e){}方法替换Exception消息?

时间:2017-08-05 15:36:57

标签: java

除了try{}catch(Exception e){}方法之外,还有一种方法可以在程序的任何地方发生像InputMismatchException,NoSuchElementException等异常时发出替换异常消息的自定义消息吗?

编辑:我想要另一种方法,因为如果我使用try{}catch(Exception e){}方法,那么我将无处不在,而且代码也会变长。

例如:

public static String genderOutput()
    {

        try
        {

            System.out.print("\nMale   - 1 \nFemale - 2 \n\nEnter either 1 or 2: ");

            int genderInput = userInput.nextInt();

            if(genderInput == 1)
            {

                String userGender = "Mr.";

                return userGender;

            }

            else if(genderInput == 2)
            {

                String userGender = "Mrs.";

                return userGender;

            }

            else
            {

                String userGender = " ";

                return userGender;

            }

        }

        catch (Exception e)
        {

            return null;

        }

    }

我有这个函数,现在如果像这样的类中有多个函数那么我必须到处都有try{}catch(Exception e){}方法。如果你可以用你自己的异常消息替换异常消息并且当发生了向他们声明的自定义消息然后它会抛出自定义消息时,它会更有效率。这样,代码也会更短。

解决我的问题:

public class Test
{

    public static Scanner userInput = new Scanner(System.in);

    public static String titleName = "TheRivalsRage";
    public static String exitLevelMessage = "Program exited!";
    public static String errorMessageTitle = "\n[Error] ";

    public static String intInputMismatchException = "Please enter an Integer Value!";
    public static String intNoSuchElementException = "Please enter either '1' or '2' without the quotes!";
    public static String lineNoSuchElementException = "Please enter something!";
    public static String bothIllegalStateException  = "Scanner closed unexpectedly!";

    public static void main(String[] args)
            throws Exception
    {

        String usernameOutput;
        String userGender;

        try
        {

            System.out.print("Enter your username: ");

            usernameOutput = userInput.nextLine();

            userGender = genderOutput();

            userInput.close();

        }

        catch(IllegalStateException e)
        {

            throw new IllegalStateException(errorMessageTitle + bothIllegalStateException);

        }

        if(userGender == null)
        {

            noSuchElementException();

        }

        else
        {

            System.out.println("\nWelcome " + userGender + " " + usernameOutput + " to " + titleName);

        }

    }

    public static String genderOutput()
    {

        String userGender;

        int genderInput;

        System.out.print("\nMale   - 1 \nFemale - 2 \n\nEnter either 1 or 2: ");

        try
        {

            genderInput = userInput.nextInt();

        }

        catch(InputMismatchException e)
        {

            genderInput = 0;

            inputMismatchException();

        }

        if(genderInput == 1)
        {

            userGender = "Mr.";

        }

        else if(genderInput == 2)
        {

            userGender = "Mrs.";

        }

        else
        {

            userGender = null;

        }

        return userGender;

    }

    public static void inputMismatchException()
            throws InputMismatchException
    {

        throw new InputMismatchException(errorMessageTitle + intInputMismatchException);

    }

    public static void noSuchElementException()
            throws NoSuchElementException
    {

        throw new NoSuchElementException(errorMessageTitle + intNoSuchElementException);

    }

}

4 个答案:

答案 0 :(得分:1)

不要在每个方法中处理异常,只需在方法签名后使用 throws Exception ,并在调用方法的末尾处理它。 在catch块中你可以抛出自定义异常。

 void method1() throws Exception{
//
}

void method2() throws Exception{
//
}

   void finalmethod(){
        try{
          method1();

          method2();

        }catch(InputMismatchException e){
                  throw customExcpetion("custommessage1");
        }catch(Exception e){
            throw customExcpetion("custommessage2");
        }
    }

答案 1 :(得分:0)

您需要try / catch

但是,您不需要单独捕获所有异常,因为您提到的异常都是RuntimeException的子类。因此,在try中生成一个catch / main来拦截RuntimeException就足够了,并打印替换消息:

public static void main(String[] args) {
    try {
        ... // Actual code
    } catch (RuntimeException ex) {
        System.err.println("A runtime error has occurred.");
    }
}

答案 2 :(得分:0)

您可以通过创建周围的建议来尝试Aspectj或Spring aop。您可以通过在建议和重新抛出中捕获异常来替换消息。

检查http://howtodoinjava.com/spring/spring-aop/aspectj-around-advice-example/ 要知道如何使用spring aop来提出建议

答案 3 :(得分:0)

Java没有提供开箱即用的功能,但没有人阻止您创建一个组成Scanner对象的类,并将您正在使用的方法装饰为nextInt()

在装饰方法内部,调用nextInt(),通过在问题中返回null来捕获它可能抛出并处理它的异常。
如果有意义,如果输入失败,您甚至可以提供一个nextInt()方法,其默认值为参数。

public class MyCustomScanner{

   private Scanner scanner;
   ...
   public Integer nextInt(){
       try{       
            return scanner.nextInt()
       }
       catch(InputMismatchException e){
           myStateObj.setErrorMessage("....");
           return null;
       }
   }
   public Integer nextInt(Integer defaultValue){
       try{       
            return scanner.nextInt()
       }
       catch(InputMismatchException e){
           myStateObj.setErrorMessage("....");
           return defaultValue;
       }
   }
}

现在您可以这样使用该类:

MyCustomScanner scanner = new MyCustomScanner();
Integer intValue = scanner.nextInt();
Integer otherIntValue = scanner.nextInt(Integer.valueOf(4));