Revise to include Exception handling

Below, there is CalculatorTest.java attached. The error handling in it mostly via some if statements etc.

Question: What is the best way to use java Exception handling routines to improve it?


import java.text.DecimalFormat;

public class CalculatorTest{
    

   public static boolean isNumeric(String s) {

        boolean b = true;

        try {
          float f = Float.parseFloat(s);
        }
        catch(Exception ex){
            b = false;
        }
            return b;
        }

        public static String validData(String [] ss){

            String temp="";

            if(!isNumeric(ss[0])) {
                temp= "Wrong Input: " + ss[0];
            }else if(!isNumeric(ss[2])) {
                temp= "Wrong Input: " + ss[2];
            }else if(Double.parseDouble(ss[2])==0.0 && ss[1].charAt(0)=='/') {
                temp= "Division by zero";
            }
            return temp;
        }

        public static String validInput(String [] ss){

//                 for(String s: ss){
//                System.out.println(s);
//            }

            String temp="";

//            System.out.println("Im here");
            if (ss.length !=3) {
                temp = "Usage: java Calculator operand1 operator operand2\n";

            }else if(!ss[1].equals("+") && !ss[1].equals("-") && !ss[1].equals("*") && !ss[1].equals("/")){
                temp = "Usage: java Calculator operand1 operator operand2\n"+
                       "       (Make sure to have * inside \"*\" as shown here.";}
            return temp;
        }

        public static void main(String[] args) {

//            for(String s: args){
//                System.out.println("|"+s+"|");
//            }

            String errorMessage = validInput(args);

//            System.out.println("Test return: "+errorMessage+"\n");

            if(errorMessage.trim().length() != 0){

                System.out.println(errorMessage+"\n");

            }else{

                errorMessage = validData(args);

                if(errorMessage.trim().length() != 0){
                    System.out.println("Error: " + errorMessage + "\n");
                    
              //  }else if(errorMessage.toString()==""){
                //    System.out.println(errorMessage + "\n");
                }else{
                    printTheCalculationresult(args);
                }
            }
        }

        public static void printTheCalculationresult(String[] args)
        {
            System.out.print("print The Calculation result: ");

            DecimalFormat df=new DecimalFormat("0.##");
            double result=0.0;


            switch (args[1].charAt(0)){
                case '+': result=(int) Double.parseDouble(args[0]) +
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '-': result=(int) Double.parseDouble(args[0]) -
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '*': result=(int)Double.parseDouble(args[0])*
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '/': result=Double.parseDouble(args[0]) /
                                 Double.parseDouble(args[2]);
            }

            System.out.print(args[0]+ " " +    args[1] + " " + args[2] + " = "+  result+"\n\n");
    }
}

Open in new window

LVL 34
Mike EghtebasDatabase and Application DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

for_yanCommented:
What do you mean by that ?
You can throw execption in all these methods and catch them in the main() program
from the place where you call them

And better to use one validation method rather than to split it between two or more
for_yanCommented:
this is an example :
change to 2 + a (instead of 2 + 3) and it will catch custom exception

import java.text.DecimalFormat;

public class TestCalculator {

   public static boolean isNumeric(String s) {

        boolean b = true;

        try {
          float f = Float.parseFloat(s);
        }
        catch(Exception ex){
            b = false;
        }
            return b;
        }

        public static void  validData(String [] ss) throws InvalidDataException {

            String temp="";

            if(!isNumeric(ss[0])) {
                temp= "Wrong Input: " + ss[0];
            }else if(!isNumeric(ss[2])) {
                temp= "Wrong Input: " + ss[2];
            }else if(Double.parseDouble(ss[2])==0.0 && ss[1].charAt(0)=='/') {
                temp= "Division by zero";
            }

            if(temp.trim().length() >0)throw new InvalidDataException(" Input invalid: non-numeric operands or invaild operations");
            //return temp;
        }

        public static String validInput(String [] ss){

                 for(String s: ss){
                System.out.println(s);
            }

            String temp="";

            System.out.println("Im here");
            if (ss.length !=3) {
                temp = "Usage: java Calculator operand1 operator operand2\n";

            }else if(!ss[1].equals("+") && !ss[1].equals("-") && !ss[1].equals("*") && !ss[1].equals("/")){
                temp = "Usage: java Calculator operand1 operator operand2\n"+
                       "       (Make sure to have * inside \"*\" as shown here.";}

            

            return temp;
        }

        public static void main(String[] args) {

            for(String s: args){
                System.out.println(s);
            }

            String errorMessage = validInput(args);

            System.out.println("Test return: "+errorMessage+"\n");

            if(errorMessage.trim().length() != 0){

                System.out.println(errorMessage+"\n");

            }else{
                   try{
               validData(args);
                   }catch(InvalidDataException ex){
                      System.out.println( ex.toString());
                       ex.printStackTrace();
                        System.out.println("Error: " + errorMessage + "\n\n" +
                        "Usage: java Calculator operand1 operator operand2\n");
                       System.exit(0);
                   }



                    printTheCalculationresult(args);
                }
            }
        

        public static void printTheCalculationresult(String[] args)
        {
            System.out.print("print The Calculation result: ");

            DecimalFormat df=new DecimalFormat("0.##");
            double result=0.0;

            switch (args[1].charAt(0)){
                case '+': result=(int) Double.parseDouble(args[0]) +
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '-': result=Integer.parseInt(args[0]) -
                                 Integer.parseInt(args[2]);
                          break;
                case '*': result=(int)Double.parseDouble(args[0])*
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '/': result=Integer.parseInt(args[0]) /
                                 Integer.parseInt(args[2]);
            }

            System.out.print(args[0]+ " " +    args[1] + " " + args[2] + " = "+  df.format(result)+"\n\n");

           
            
    }
}
class InvalidDataException extends Exception {
    String mistake;
    public  InvalidDataException(String err)
     {
       super(err);     // call super class constructor
       mistake = err;  // save message
     }

    public String toString(){
        return mistake;
    }

    

}

Open in new window

Mike EghtebasDatabase and Application DeveloperAuthor Commented:
Using NumberFormatException and/ or creating our own exception class.
Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

for_yanCommented:
The above is example with our own exception class
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
NumberFormatException is a subclass of the Runtime Exception class.  A Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values.

How can include NumberFormatException with it?
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
re:> The above is example with our own exception class

I am learning but what I meant to have a separate Exception class where we can instantiate it in our main() and use it that way. However, finding use and reference to NumberFormatException is my prime goal.  
for_yanCommented:
Yes number formaty excpetion will be thwon if  Integer.parseInt("abc") - so you can catch it and re-thow back from your method
for_yanCommented:
The above code does have separate execption class - see below
for_yanCommented:
You dont nweed to instantiate sException class necessaruily in main() - you need  to do it
when you throw exception - look at the code above
for_yanCommented:
try this code with

2 + a

and

with

2 / 0

you'll see how it catches different exceptions

I think I in the emantime removed chacking ofr the type of operand - but that
is not important for the sake of understadning how it works

import java.text.DecimalFormat;
import java.util.IllegalFormatException;

public class TestCalculator {

   public static void isNumeric(String s) throws NumberFormatException {

        boolean b = true;

        try {
          float f = Float.parseFloat(s);
        }
        catch(NumberFormatException ex){
            b = false;
            throw ex;
        }
            //return b;
        }

        public static void  validData(String [] ss) throws InvalidDataException, NumberFormatException {

            String temp="";

            try {
            isNumeric(ss[0]);
                isNumeric(ss[2]);
            }catch(IllegalFormatException ex){
             throw ex;
            }

           if(Double.parseDouble(ss[2])==0.0 && ss[1].charAt(0)=='/') {
                temp= "Division by zero";
            }

            if(temp.trim().length() >0)throw new InvalidDataException(" Input invalid: division by zero");
            //return temp;
        }

        public static String validInput(String [] ss){

                 for(String s: ss){
                System.out.println(s);
            }

            String temp="";

            System.out.println("Im here");
            if (ss.length !=3) {
                temp = "Usage: java Calculator operand1 operator operand2\n";

            }else if(!ss[1].equals("+") && !ss[1].equals("-") && !ss[1].equals("*") && !ss[1].equals("/")){
                temp = "Usage: java Calculator operand1 operator operand2\n"+
                       "       (Make sure to have * inside \"*\" as shown here.";}

            

            return temp;
        }

        public static void main(String[] args) {

            for(String s: args){
                System.out.println(s);
            }

            String errorMessage = validInput(args);

            System.out.println("Test return: "+errorMessage+"\n");

            if(errorMessage.trim().length() != 0){

                System.out.println(errorMessage+"\n");

            }else{
                   try{
               validData(args);
                   }catch(InvalidDataException ex){
                      System.out.println( ex.toString());
                     //  ex.printStackTrace();
                        System.out.println("Error: " + errorMessage + "\n\n" +
                        "Usage: java Calculator operand1 operator operand2\n");
                       System.exit(0);
                   }  catch( NumberFormatException ex1){
                         System.out.println( ex1.toString());
                    //   ex1.printStackTrace();
                        System.out.println(
                        "Usage: java Calculator operand1 operator operand2\n");
                       System.exit(0);

                   }



                    printTheCalculationresult(args);
                }
            }
        

        public static void printTheCalculationresult(String[] args)
        {
            System.out.print("print The Calculation result: ");

            DecimalFormat df=new DecimalFormat("0.##");
            double result=0.0;

            switch (args[1].charAt(0)){
                case '+': result=(int) Double.parseDouble(args[0]) +
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '-': result=Integer.parseInt(args[0]) -
                                 Integer.parseInt(args[2]);
                          break;
                case '*': result=(int)Double.parseDouble(args[0])*
                                 (int) Double.parseDouble(args[2]);
                          break;
                case '/': result=Integer.parseInt(args[0]) /
                                 Integer.parseInt(args[2]);
            }

            System.out.print(args[0]+ " " +    args[1] + " " + args[2] + " = "+  df.format(result)+"\n\n");

           
            
    }
}
class InvalidDataException extends Exception {
    String mistake;
    public  InvalidDataException(String err)
     {
       super(err);     // call super class constructor
       mistake = err;  // save message
     }

    public String toString(){
        return mistake;
    }

    

}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.