?
Solved

Revise to include Exception handling

Posted on 2011-10-03
10
Medium Priority
?
266 Views
Last Modified: 2012-05-12
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

0
Comment
Question by:Mike Eghtebas
  • 7
  • 3
10 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36905076
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36905217
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
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36905231
Using NumberFormatException and/ or creating our own exception class.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 47

Expert Comment

by:for_yan
ID: 36905238
The above is example with our own exception class
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36905258
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
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36905282
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36905291
Yes number formaty excpetion will be thwon if  Integer.parseInt("abc") - so you can catch it and re-thow back from your method
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36905308
The above code does have separate execption class - see below
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36905320
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
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36905403
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question