-1

Instead of the try{}catch(Exception e){} method, is there a way to just state a custom message that replaces the exception message when exceptions like InputMismatchException, NoSuchElementException etc. occurs anywhere on the program?

EDIT: I want another method because if I use try{}catch(Exception e){} method than I will have to do it everywhere and the code also becomes longer.

For example:

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;

        }

    }

I have this function, now if there were multiple functions in a class like this then I would have to have the try{}catch(Exception e){} method everywhere. Wouldn't it be more efficient if you can just replace the exception message with your own and when such exception occurs which has a custom message stated to them then it would just throw out the custom message instead. This way, the code will be shorter as well.

SOLUTION TO MY PROBLEM:

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

    }

}
RedAISkye
  • 37
  • 9

4 Answers4

1

don't handle exception in each and every method just use throws Exception after method signature and handle it at end where the methods are being called. and there in catch block you can throw your custom exception.

 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");
        }
    }
user2862544
  • 415
  • 3
  • 13
0

You need a try/catch.

However, you do not need to catch all exceptions separately, because the exceptions that you mention are all subclasses of RuntimeException. Hence, it is sufficient to make a single try/catch in your main to intercept RuntimeException, and print the replacement message:

public static void main(String[] args) {
    try {
        ... // Actual code
    } catch (RuntimeException ex) {
        System.err.println("A runtime error has occurred.");
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • This is a better way of doing it but will it work on functions when they are called as well? – RedAISkye Aug 05 '17 at 15:50
  • But for example: InputMismatchException and NoSuchElementException are different errors so they'll have their own message and not a single message. – RedAISkye Aug 06 '17 at 15:02
0

You can try Aspectj or Spring aop by creating around advice. You can replace message by catching exception inside advice and rethrow.

Check http://howtodoinjava.com/spring/spring-aop/aspectj-around-advice-example/ To know about how to use spring aop for anound advice

Noman Khan
  • 920
  • 5
  • 12
  • I'm a beginner so that will be too much for me right now. I just want some kind of method on the Java itself. – RedAISkye Aug 05 '17 at 15:55
0

Java doesn't provide this feature out of the box but nobody prevents you to create a class that composes a Scanner object and that decorates methods that you are using as nextInt().

Inside the decorated method, invoke nextInt(), catch the exception that it may throw and handle it by returning null as in your question.
If it makes sense, you could even provide a nextInt() method with a default value as parameter if the input fails.

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

Now you can use the class in this way :

MyCustomScanner scanner = new MyCustomScanner();
Integer intValue = scanner.nextInt();
Integer otherIntValue = scanner.nextInt(Integer.valueOf(4));
davidxxx
  • 125,838
  • 23
  • 214
  • 215