Link to home
Start Free TrialLog in
Avatar of Mike Eghtebas
Mike EghtebasFlag for United States of America

asked on

try/catch

Because in try block, we have:

throw new NumberFormatException(s+" is not a hex number.");

so, do we still need to repeat it in the catch block like:

//throw new InvalidDataException13_6 (s +" is not a hex number.");

which is removed.

Thank you.
for(int i=0; i<str.length();i++) 
        {
            s=str.substring(i,i+1);  

            try{
                if(!isHex(s))
                throw new NumberFormatException(s+" is not a hex number.");

                char S=s.charAt(i);
                int t =(int)S;
                temp=t*(int)Math.pow(16,str.length()-i-1);

            } catch(Exception ex){
                //throw new InvalidDataException13_6 (s +" is not a hex number.");
            }

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image

We should understan followin - you either want the method to throw excception
and than you writye in the method "throws NumberFormatException" and then you cath Exception in your calling code
or you catch exception inside the the method
You can do eaither of two ways - and it depnds where it is more conveneinet fopr you to catch exception
and where to inform the user about the problem and how you organize your develipemnt - which people are writing which code
All those ways are possible.

Also if you don't want to throw NumberFormatException which has the message which was written by Java
developers etc, but waht to do more explanation for the user in the context of your application- then you can catch NumberFormatException
and thrwo your own custom exception and devise your own message with the contest of your appliaction
Avatar of Mike Eghtebas

ASKER

I will go back and do more reading. But for now, if you may debug the attache code so I would lean by example. The code has revised to make sure it is calculating correctly.

BTW, these are from a book but they are not school work. I tend to go through all the chapters and do all the problems.

Thanks
import java.util.Scanner;

public class Exercise13_6{

    public static void main(String[] args) throws
        InvalidDataException13_6, NumberFormatException {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a hex number: ");
        String hex=input.nextLine();
        System.out.println("The decimal value for hex number "
                + hex + " is " + hexToDecimal(hex.toUpperCase()));
    }

    public static int hexToDecimal(String str) 
            throws InvalidDataException13_6, NumberFormatException {

        int sum=0;     
        int temp=0;
        String s="";
           int i=0;
            try{
                for( i=0; i<str.length();i++) 
                {
                    s=str.substring(i,i+1);                
                    if(!isHex(s)){
                        throw new NumberFormatException(s+" is not a hex number.");
                }else{
                    
                    char S=s.charAt(0);
                    int t =0;
                    if(S>='A' && S<='F')
                        t =(int)S-'A'+10;
                    else
                        t = S - '0';
                    temp=t*(int)Math.pow(16,str.length()-i-1);
//                    System.out.println("temp: "+temp+", "+(str.length()-i-1));
//                }
                    sum=sum+temp;
                }                      
            } catch(Exception ex){
                throw InvalidDataException13_6 ex= new InvalidDataException13_6 (s +" is not a hex number.");
                System.out.println(ex.toString());
            }
//System.out.println(sum);
        return sum;
                    
    }

    public static boolean isHex(String str) 
    {
            return ("0123456789ABCDEF".indexOf(str) > -1);
    }

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

        public String toString(){
            return mistake;
        }
    }
}

Open in new window

This is working.


import java.util.Scanner;

public class Exercise13_6{

    public static void main(String[] args) throws
        InvalidDataException13_6, NumberFormatException {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a hex number: ");
        String hex=input.nextLine();
        System.out.println("The decimal value for hex number "
                + hex + " is " + hexToDecimal(hex.toUpperCase()));
    }

    public static int hexToDecimal(String str)
            throws InvalidDataException13_6, NumberFormatException {

        int sum=0;
        int temp=0;
        String s="";
           int i=0;
            try{
                for( i=0; i<str.length();i++)
                {
                    s=str.substring(i,i+1);
                    if(!isHex(s)){
                        throw new NumberFormatException(s+" is not a hex number.");
                }else{

                    char S=s.charAt(0);
                    int t =0;
                    if(S>='A' && S<='F')
                        t =(int)S-'A'+10;
                    else
                        t = S - '0';
                    temp=t*(int)Math.pow(16,str.length()-i-1);
//                    System.out.println("temp: "+temp+", "+(str.length()-i-1));
//                }
                    sum=sum+temp;
                }
                }
            } catch(Exception ex){
                throw  new InvalidDataException13_6 (s +" is not a hex number.");
                //System.out.println(ex.toString());
            }
//System.out.println(sum);
        return sum;

    }

    public static boolean isHex(String str)
    {
            return ("0123456789ABCDEF".indexOf(str) > -1);
    }


}

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

        public String toString(){
            return mistake;
        }
    }

Open in new window


Enter a hex number: 0fc1de
The decimal value for hex number 0fc1de is 1032670

Open in new window


Enter a hex number: 012fgfe
Exception in thread "main" G is not a hex number.
	at Exercise13_6.hexToDecimal(Exercise13_6.java:42)
	at Exercise13_6.main(Exercise13_6.java:10)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)

Open in new window

What kind of changes will make it just to display just two top lines:

Enter a hex number: 012fgfe
Exception in thread "main" G is not a hex number.


But not the rest:

      at Exercise13_6.hexToDecimal(Exercise13_6.java:42)
      at Exercise13_6.main(Exercise13_6.java:10)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
      at java.lang.reflect.Method.invoke(Method.java:597)
      at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial