[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Expanding exception handling

Posted on 2011-10-07
33
Medium Priority
?
309 Views
Last Modified: 2012-05-12
I added InvalidDataException1 to this line:
   
public static int findSumIn(String s)
           throws NumberFormatException, WrongNumberOfInputsException, InvalidDataException1 {

In order to be able to add two new try{} to check on the validity of input data.

Operation: User to enter 4 5 to get 9 (no operator necessary). If

a 6   <-- invalid data, then prompt the user (after giving error message) to try it again.

The code below works in NetBeans but it gives 3 compile errors (complaining about InvalidDataException1).

Could you see where the problem is?

Thank you.
import java.util.Scanner;

public class Exercise13_2 {

   static int number1;
   static int number2;

   public static void main(String[] args) {

        boolean terminate=false;

        while(terminate==false) {
            
            Scanner input=new Scanner(System.in);
            System.out.println("Enter two integers (ex. 2 4) to get the sum 6:");
            String str = input.nextLine();
            
            try{
                Integer result=findSumIn(str);
                System.out.println("Sum of two integers is: " + result +"\n");
                terminate=true;
            } catch(Exception ex){
                System.out.println(ex);
            }
        }
   }
   
   public static int findSumIn(String s) 
           throws NumberFormatException, WrongNumberOfInputsException, InvalidDataException1 {

        String[] inputs = s.split(" ");

        try {
            if(inputs.length!=2)
                throw new WrongNumberOfInputsException("You need to enter two args\n");       
        }
        catch(NumberFormatException ex){
            throw ex;
        }
        
        try {
            number1=Integer.parseInt(inputs[0]);      
        }catch(NumberFormatException ex){
             throw new InvalidDataException1 ("Wrong Input:  " + inputs[0]);        
        }

        try {
            number2=Integer.parseInt(inputs[1]);      
        }catch(NumberFormatException ex){
             throw new InvalidDataException1 ("Wrong Input:  " + inputs[1]);        
        }
        
        return number1+number2;
   }
    
}

class  WrongNumberOfInputsException extends Exception {
    private String s;
    public   WrongNumberOfInputsException(String s){
        this.s = s;
    }

    public String toString() {return s;}

}

Open in new window

0
Comment
Question by:Mike Eghtebas
  • 14
  • 13
  • 5
  • +1
33 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36934860
I see no compilation errors

Perhaps you have class
WrongNumberOfInputsException
already in the same Project and therefore you see the conflict

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934865
I have no problem with InvalidDataException1

I think you have some issue with duplicate class in the project, because you had the same classes within another file
0
 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 36934866
<<The code below works in NetBeans but it gives 3 compile errors (complaining about InvalidDataException1).>>
Is InvalidDataException1 class there in the same package? and compiled successfully?
If not, please import that class
0
Technology Partners: 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 34

Author Comment

by:Mike Eghtebas
ID: 36934874
I copied it to desktop and tried to compile it. see the image:
Exercise13-2CompileError.png
0
 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 36934877
Then the reason is one of those mentioned in my previous post only.

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934878
You probably have it named InvalidDataException
Check that - I mentioned that I renamed it
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934881

create package exercise132 in NetBeans
and put the code below into that package - then
it should work and should not clash with your previous classes

package exercise132;

import java.util.Scanner;

public class Exercise13_2 {

   static int number1;
   static int number2;

   public static void main(String[] args) {

        boolean terminate=false;

        while(terminate==false) {
            
            Scanner input=new Scanner(System.in);
            System.out.println("Enter two integers (ex. 2 4) to get the sum 6:");
            String str = input.nextLine();
            
            try{
                Integer result=findSumIn(str);
                System.out.println("Sum of two integers is: " + result +"\n");
                terminate=true;
            } catch(Exception ex){
                System.out.println(ex);
            }
        }
   }
   
   public static int findSumIn(String s) 
           throws NumberFormatException, WrongNumberOfInputsException, InvalidDataException1 {

        String[] inputs = s.split(" ");

        try {
            if(inputs.length!=2)
                throw new WrongNumberOfInputsException("You need to enter two args\n");       
        }
        catch(NumberFormatException ex){
            throw ex;
        }
        
        try {
            number1=Integer.parseInt(inputs[0]);      
        }catch(NumberFormatException ex){
             throw new InvalidDataException1 ("Wrong Input:  " + inputs[0]);        
        }

        try {
            number2=Integer.parseInt(inputs[1]);      
        }catch(NumberFormatException ex){
             throw new InvalidDataException1 ("Wrong Input:  " + inputs[1]);        
        }
        
        return number1+number2;
   }
    
}

class  WrongNumberOfInputsException extends Exception {
    private String s;
    public   WrongNumberOfInputsException(String s){
        this.s = s;
    }

    public String toString() {return s;}

}

class InvalidDataException1 extends Exception { String mistake;
    public  InvalidDataException1(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: 36934882
re:> Then the reason is one of those mentioned in my previous post only.

-It works ok in Netbeans

- When I changed (removed some parts) as shown below it compile. but of course the input integer are not being changed.

The whole idea was to have 3 try{} instead of one for detail exception handling purpose.
public static int findSumIn(String s) 
           throws NumberFormatException, WrongNumberOfInputsException, InvalidDataException1 {

        String[] inputs = s.split(" ");

        try {
            if(inputs.length!=2)
                throw new WrongNumberOfInputsException("You need to enter two args\n");       
        }
        catch(NumberFormatException ex){
            throw ex;
        }
        
        try {
            number1=Integer.parseInt(inputs[0]);      
        }catch(NumberFormatException ex){
             throw new InvalidDataException1 ("Wrong Input:  " + inputs[0]);        
        }

        try {
            number2=Integer.parseInt(inputs[1]);      
        }catch(NumberFormatException ex){
             throw new InvalidDataException1 ("Wrong Input:  " + inputs[1]);        
        }
        
        return number1+number2;
   }

Open in new window

public static int findSumIn(String s) 
           throws NumberFormatException, WrongNumberOfInputsException {

        String[] inputs = s.split(" ");

        try {
            if(inputs.length!=2)
                throw new WrongNumberOfInputsException("You need to enter two args\n");       
        }
        catch(NumberFormatException ex){
            throw ex;
        }
               
        return number1+number2;
   }

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934883
No sorry, i pasted your old exception class. just a moment
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934887
Paste the whole class as you are using it now and explain what you  want to see
0
 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 36934890
<<-It works ok in Netbeans>>
You can always specify classpath and add dependent projects in netbeans, which you may forget to do in command line

Please check again
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934891
You probably should name exception classes with the same ending as your execrcise number and class name -
and alwys keep them in the same file - otherwise you'll have these issues with clashes
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934899
One or more projects were compiled with errors.

With InvalidDataException1 underlined red in 3 places
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934901
Hover over the red - it will tell you that it cannot find symbol or that it has duplicate symbol
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934904
re:> You can always specify classpath and add dependent projects in netbeans, which you may forget to do in command line

I am not sure if it refers to an outside class. I am not sure.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934905
Do you have each exercise in the separate project ?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934906
No don't go away from Netbeans to command line and you don't have anything to specify in dependencies - all of them are in your code
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934909
I am lost. Not sure. I will check to see if it have it in netbean folder or in another project under a different project.
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934911
It has to be something with the same name, right?
0
 
LVL 4

Expert Comment

by:stachenov
ID: 36934913
Compiles fine for me from command line, given that InvalidDataException1 is declared in the file named "InvalidDataException1.java" in the same directory as "Exercise13_2.java", so please double-check that.

Once you got that working from command line, you'd better re-create your Netbeans project from scratch, putting those two files in a separate directory and using the "Create new project from existing sources" option, since it could be some sort of Netbeans bug. I remember it not finding my classes before.
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934916
in the process of house cleaning I have deleted couple of files. Most likely the damage is done then.

- I can get it back from windows 7 trash beans.
- most likely it is somewhere i=posted at EE oct 3 or 4th
- It is in a netbeans folder
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36934921
Create new project in Netbeans.
Create new class Exercise13_2 in defaiult package
and paste the whole code below into that
class - including two Exceptions non=public classes at the bottom of the code below
Then compile and run - it should work (see output below):


import java.util.Scanner;

public class Exercise13_2 {

   static int number1;
   static int number2;

   public static void main(String[] args) {

        boolean terminate=false;

        while(terminate==false) {

            Scanner input=new Scanner(System.in);
            System.out.println("Enter two integers (ex. 2 4) to get the sum 6:");
            String str = input.nextLine();

            try{
                Integer result=findSumIn(str);
                System.out.println("Sum of two integers is: " + result +"\n");
                terminate=true;
            } catch(Exception ex){
                System.out.println(ex);
            }
        }
   }

   public static int findSumIn(String s)
           throws NumberFormatException, WrongNumberOfInputsException, InvalidDataException1 {

        String[] inputs = s.split(" ");

        try {
            if(inputs.length!=2)
                throw new WrongNumberOfInputsException("You need to enter two args\n");
        }
        catch(NumberFormatException ex){
            throw ex;
        }

        try {
            number1=Integer.parseInt(inputs[0]);
        }catch(NumberFormatException ex){
             throw new InvalidDataException1 ("Wrong Input:  " + inputs[0]);
        }

        try {
            number2=Integer.parseInt(inputs[1]);
        }catch(NumberFormatException ex){
             throw new InvalidDataException1 ("Wrong Input:  " + inputs[1]);
        }

        return number1+number2;
   }

}

class  WrongNumberOfInputsException extends Exception {
    private String s;
    public   WrongNumberOfInputsException(String s){
        this.s = s;
    }

    public String toString() {return s;}

}

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

    public String toString(){
        return mistake;
    }
}

Open in new window



Enter two integers (ex. 2 4) to get the sum 6:
a 4
Wrong Input:  a
Enter two integers (ex. 2 4) to get the sum 6:
4/5 3
Wrong Input:  4/5
Enter two integers (ex. 2 4) to get the sum 6:
3 6
Sum of two integers is: 9

Open in new window

0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934922
I found the file. I am compiling again.
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934923
ok, I will do your solution first
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934925
error:

class InvalidDataException1 extends Exception { String mistake;
    public  InvalidDataException1(String err)

duplicate class
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934927
But it should be okay outside netbeans, I will try now
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934930
I work thanks.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934933
This code should work both in Netbeans and outside - if you put the whole code in one class


import java.util.Scanner;

public class Exercise13_2 {

   static int number1;
   static int number2;

   public static void main(String[] args) {

        boolean terminate=false;

        while(terminate==false) {

            Scanner input=new Scanner(System.in);
            System.out.println("Enter two integers (ex. 2 4) to get the sum 6:");
            String str = input.nextLine();

            try{
                Integer result=findSumIn(str);
                System.out.println("Sum of two integers is: " + result +"\n");
                terminate=true;
            } catch(Exception ex){
                System.out.println(ex);
            }
        }
   }

   public static int findSumIn(String s)
           throws NumberFormatException, WrongNumberOfInputsException132, InvalidDataException132 {

        String[] inputs = s.split(" ");

        try {
            if(inputs.length!=2)
                throw new WrongNumberOfInputsException132("You need to enter two args\n");
        }
        catch(NumberFormatException ex){
            throw ex;
        }

        try {
            number1=Integer.parseInt(inputs[0]);
        }catch(NumberFormatException ex){
             throw new InvalidDataException132 ("Wrong Input:  " + inputs[0]);
        }

        try {
            number2=Integer.parseInt(inputs[1]);
        }catch(NumberFormatException ex){
             throw new InvalidDataException132 ("Wrong Input:  " + inputs[1]);
        }

        return number1+number2;
   }

}

class  WrongNumberOfInputsException132 extends Exception {
    private String s;
    public   WrongNumberOfInputsException132(String s){
        this.s = s;
    }

    public String toString() {return s;}

}

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

    public String toString(){
        return mistake;
    }
}

Open in new window

0
 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 36934934
so it means there is some dependency which you have specified in Netbeans which you didn't specified on command line, right?
0
 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 36934936
glad that it worked for you.
@for_yan: you have a patience of a Saint. Good work
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934937
Do it better this way - keep your Exceptions with the main class and give them
modified names like inmy last code - you'll have no clashes.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36934940
gurvinder, thanks  for the kind words.
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36934951
Yes that is what I should do. Now I know better.

I have damaged lots of file this way. I have to go over them on the weekend,

Thank you.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month18 days, 21 hours left to enroll

834 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