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

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

0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
Using NumberFormatException and/ or creating our own exception class.
0
 
for_yanCommented:
The above is example with our own exception class
0
 
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?
0
 
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.  
0
 
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
0
 
for_yanCommented:
The above code does have separate execption class - see below
0
 
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.