Results 1 to 12 of 12
  1. #1
    kewlgeye is offline Member
    Join Date
    Apr 2008
    Posts
    34
    Rep Power
    0

    Red face Try Catch block issues

    I have this code and this code isn't displaying properly. It compiles, and then it asks the first question but when I press enter it just displays a blank line. and then I press enter again and it displays my program ending statement. What is wrong with this code? My responses are suppose to be only "y" or "n" and anything else is suppose to throw an exception or error returning the user back to the original question. I haven't figured that out yet.
    Here is the Code:

    Java Code:
    import java.io.*;
    
    class ModifiedTest
    {
    	public static void main(String args[]) throws IOException
    	{
    		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
    		BufferedReader dataIn1 = new BufferedReader(new InputStreamReader(System.in));
    		String strInput;
    		String strInput1;
    		String strInput2;
    		int intInput = 0;
    		int intInput1 = 0;
    
    
    		try
    		{
    			System.out.println("Do you like Rock Music?:");
    			strInput = dataIn.readLine();  //reads data from console
    			
                            System.out.println();
    			if (strInput == "n")
    			{
    				throw new TheException(); //calls 
    			}
                            else
    			
    			if (strInput == "y")
    			System.out.println("Do you like Marilyn Manson?:");
    			strInput1 = dataIn1.readLine();  //reads data from console
    		
    			System.out.println();
    			if (strInput1 == "n")
    			{
    				throw new TheException(); //calls 
    			}
                            else
    			if (strInput1 == "y")
    			System.out.println("You are a hardcore Rocker");
    			
    			
    
    		}
    
    		catch (TheException e) 
    		{
    			System.out.println("" + e);
    		}
                    System.out.println();
    		System.out.println("Program Ending!");
    	}
    
    }
    
    class TheException extends Exception
    {
    	public String toString()
    	{
    		return "How could you not like Marilyn Manson?";
    	}
    }

  2. #2
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Hello,

    This is not a try/catch block issue. I guess you are a beginner to Java and maybe a beginner to programming. There are lots of problems with the code you presented:

    - In Java you almost never compare strings with "==". There are a few situations but only used by people who know what they are doing. When you compare with "==" like in strInput == "y" you will always get a false no matter what the value of StrInput is. This is because you actually compare the references to those strings and they are almost sure to be different. To compare strings you should do something like "y".equals(strInput). This will do what you want comparing the actual string values.
    - You are using exceptions for flow control. This is a technique that is always wrong. You should use plain if statements. You throw an exception instead of treating the "n" case in a normal way. On the other hand you don't treat all the other situations. What happens if I type "w"?
    - As I said before throwing an exception and catching it in the same function is a mistake. I guess it is just an attempt to do flow control. It is better to do it with if. Keep in mind it is always better to use all the language features in the spirit they way designed.

    And because by this point you may think I am a meanie here is a piece of code that works:

    Java Code:
    import java.io.*;
    
    class ModifiedTest
    {
        public static void main(String args[]) throws IOException
        {
            BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
            String strInput;
    
            System.out.println("Do you like Rock Music?:");
            strInput = dataIn.readLine();  //reads data from console
    
            if ("y".equals(strInput))
            {
                System.out.println("Do you like Marilyn Manson?:");
                strInput = dataIn.readLine();  //reads data from console
                if ("y".equals(strInput))
                {
                    System.out.println("You are a hardcore Rocker");
                }
                else if ("n".equals(strInput))
                {
                    System.out.println("How could you not like Marilyn Manson?");
                }
                else
                {
                    System.out.println("Illegal input: " + strInput);
                }
            }
            else if ("n".equals(strInput))
            {
                System.out.println("Ok, bye rock hater!");
            }
            else
            {
                System.out.println("Illegal input: " + strInput);
            }
    
            System.out.println();
            System.out.println("Program Ending!");
        }
    }
    For such an example you don't need exceptions. If you actually want to learn more about exceptions you can read my tutorial at Exceptional Java - Thoughts on Java exceptions | Little Tutorials
    Enjoy :)
    Last edited by danielstoner; 04-28-2008 at 02:29 AM.
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  3. #3
    sukatoa's Avatar
    sukatoa is offline Senior Member
    Join Date
    Jan 2008
    Location
    Cebu City, Philippines
    Posts
    556
    Rep Power
    7

    Default

    When you compare with "==" like in strInput == "y" you will always get a false no matter what the value of StrInput is. This is because you actually compare the references to those strings and they are almost sure to be different.
    Are you sure?

    How about this,
    Java Code:
    String t1 = "a";
    		String t2 = "e";
    		String t3 = "i";
    		String t4 = "o";
    		String t5 = "u";
    		if(t1 == "a"){
    			if(t4 == "o"){
    				if(t2 == "e"){
    					if(t5 == "u"){
    						if(t3 == "i"){
    							System.out.println("Comparison successful");
    						}
    					}
    				}
    			}
    		}
    freedom exists in the world of ideas

  4. #4
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Quote Originally Posted by sukatoa View Post
    Are you sure?
    I have a doubt too. See the following simple code.

    Java Code:
            String str1 = "aba";
            String str2 = "aba";
            
            if(str1 == str2)
                System.out.println("Yes");
            else
                System.out.println("No");
    Still you got the output 'Yes' on it. But, this is not legal(may be for me ;) ). Illegal not points that it is incorrect. So, why it is illegal?

    Here what I know. == operator check that both objects are exactly the same. So, two strings may be different object, in a rare case even they have exactly the same characters. Isn't it?

  5. #5
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Eranga and Sukatoa,

    Sorry for not giving a full explanation above but here it is with code examples. First my statement above is correct. You both get true from your comparisons in the samples you posted because the compiler looks at constants like "abc" and since they are immutable it optimizes them by storing them only once. So no matter how many times you declare a String like "abc" it will most likely be created only once by the compiler. But this is not guaranteed behavior. Most modern compilers do this but not all of them. So you should not base your code on this kind of behavior because for sure it will break sooner or later. Here is a code sample that shows on most compilers how this works:

    Java Code:
    import java.io.*;
    
    public class StrCmpTest
    {
        public static void main(String[] args) throws Exception
        {
            String strInput = "y";
    
            if (strInput == "y")
            {
                System.out.println("Yes");
            }
            else
            {
                System.out.println("No");
            }
        }
    }
    In this case with most compilers and modern JVMs you get "Yes". But this is by chance.

    If we get our String from the console from example, introduced by the user then we can see how this behavior might trick us. Run the next piece of code:
    Java Code:
    import java.io.*;
    
    public class StrCmpTest
    {
        public static void main(String[] args) throws Exception
        {
            BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Type y or n: ");
            String strInput = dataIn.readLine();
    
            if (strInput == "y")
            {
                System.out.println("Yes");
            }
            else
            {
                System.out.println("No");
            }
        }
    }
    Type "y" at the console and you will see how you get a "No" on the screen. No matter what you type you will get a "No".

    Now replace the if/else block in the above code with:

    Java Code:
            if ("y".equals(strInput))
            {
                System.out.println("Yes");
            }
            else
            {
                System.out.println("No");
            }
    When you type "y" now you will get the right answer "Yes".
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  6. #6
    sukatoa's Avatar
    sukatoa is offline Senior Member
    Join Date
    Jan 2008
    Location
    Cebu City, Philippines
    Posts
    556
    Rep Power
    7

    Default

    Absolutely....
    freedom exists in the world of ideas

  7. #7
    sanjeevtarar's Avatar
    sanjeevtarar is offline Senior Member
    Join Date
    Apr 2008
    Location
    Jaipur(India)
    Posts
    318
    Rep Power
    7

    Default

    Quote Originally Posted by danielstoner View Post
    Eranga and Sukatoa,

    Sorry for not giving a full explanation above but here it is with code examples. First my statement above is correct. You both get true from your comparisons in the samples you posted because the compiler looks at constants like "abc" and since they are immutable it optimizes them by storing them only once. So no matter how many times you declare a String like "abc" it will most likely be created only once by the compiler. But this is not guaranteed behavior. Most modern compilers do this but not all of them. So you should not base your code on this kind of behavior because for sure it will break sooner or later. Here is a code sample that shows on most compilers how this works:

    Java Code:
    import java.io.*;
    
    public class StrCmpTest
    {
        public static void main(String[] args) throws Exception
        {
            String strInput = "y";
    
            if (strInput == "y")
            {
                System.out.println("Yes");
            }
            else
            {
                System.out.println("No");
            }
        }
    }
    In this case with most compilers and modern JVMs you get "Yes". But this is by chance.

    If we get our String from the console from example, introduced by the user then we can see how this behavior might trick us. Run the next piece of code:

    Java Code:
    import java.io.*;
    
    public class StrCmpTest
    {
        public static void main(String[] args) throws Exception
        {
            BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Type y or n: ");
            String strInput = dataIn.readLine();
    
            if (strInput == "y")
            {
                System.out.println("Yes");
            }
            else
            {
                System.out.println("No");
            }
        }
    }
    Type "y" at the console and you will see how you get a "No" on the screen. No matter what you type you will get a "No".

    Now replace the if/else block in the above code with:

    Java Code:
            if ("y".equals(strInput))
            {
                System.out.println("Yes");
            }
            else
            {
                System.out.println("No");
            }
    When you type "y" now you will get the right answer "Yes".


    Hello Danielstoner,

    You are saying the above behavior is by chance.....Nothing is by chance in Java.

    "==" : Check for Memory References of Objects.
    "equals()" : Check for data of Objects.

    When you create a String Variable like :
    Java Code:
    String  str = "abc";
    Compiler creates it into Heap for memory utilization.
    Next time when you same String Object with same string ... JVM will look into heap and will point it to the existing If Exist.

    Java Code:
    String  str2 = "abc";
    So when you compare with "==" Operator it will give true. Because memory references are same.

    But If you create String Object like this :
    Java Code:
    String str = new String("abc");
    String str1 = new String("abc");
    It will always create New memory for the object, no matter it exist in pool or not.
    When you compare these two by "==" operator it will always give "false".Because memory references are different.

    And Now if take a case of Console.

    Java Code:
    BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
    You are always using "new" Operator and it will always create new memory space. So "==" Operator will always give you "false" because memory references are always different.
    And when you use "equals()" it will check for contents. So it will return "true"

    The behavior is not tricky it is same.




    Last edited by sanjeevtarar; 04-28-2008 at 02:42 PM.
    sanjeev,संजीव

  8. #8
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Hello Sanjeev :)

    I agree that nothing is by chance in Java... or almost nothing :) What I want to actually make clear is that while the Java behavior is not by chance, if you use "==" to compare String instances your program's behavior is left to chance. When you are calling an API method that returns a String instance you might not know how the String instance was created. It could be created with "new" or it could be a reference to a constant. So depending on what the API implementor did your code might function as expected or not. In my opinion doing a deep comparison with equals() is safer as long as the classes actually overrides equals().
    In theory you can protect yourself by using on all the String instances received from APIs the String.intern() call:
    String (Java Platform SE 6)
    But this is a bit clumsy and not a mainstream programming practice in Java. I am not even sure how many programmers actually know this method exists. And on top of that the method is native:
    Java Code:
    public native String intern();
    This means it is actually JVM dependent and we cannot know what its implementation is. In my opinion the Java specification mandates String literals to be reused for optimization purposes. On the other hand all String instances created at runtime are not added to the string literal pool.
    As a conclusion, in my opinion, while you can control everything in small examples when you write all the code, in real world coding situations when you use third party APIs and you don't know the source of your string instance, you are safer with using equals() than "==".
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  9. #9
    kewlgeye is offline Member
    Join Date
    Apr 2008
    Posts
    34
    Rep Power
    0

    Default To All:

    Thank you all who have contributed to this post. Your explanations about each others coding is helping me to better understand Java.

    danielstone your code worked well for me, however, I was also trying to use Try Catch statements for anything other than "y" or "n" And your statements are only if else statements.

    And believe me, I thought you explained quite well, and don't consider you a meanie. I thought your post was very professional.

    Thanks

  10. #10
    kewlgeye is offline Member
    Join Date
    Apr 2008
    Posts
    34
    Rep Power
    0

    Default Ok, With Catch and Try Statements

    Ok, I need this code to have catch and try statements but I keep getting a compiler error telling me I can't have catch without try, or try without catch. I don't understand, but I need my code to have catch and try statements. What can I do?

    Java Code:
    import java.io.*;
    
    class ModifiedTest
    {
        public static void main(String args[]) throws IOException
        {
            BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
            String strInput;
    
            System.out.println("Do you like Rock Music?:");
            strInput = dataIn.readLine();  //reads data from console
    
    try
    {
            
    	if ("y".equals(strInput))
            {
                System.out.println("Do you like Marilyn Manson?:");
                strInput = dataIn.readLine();  //reads data from console
                if ("y".equals(strInput))
                {
                    System.out.println("You are a hardcore Rocker");
                }
                else if ("n".equals(strInput))
                {
                    System.out.println("How could you not like Marilyn Manson?");
                }
                else
                {
                    System.out.println("Illegal input: " + strInput);
                }
            }
            else if ("n".equals(strInput))
            {
                System.out.println("Ok, bye rock hater!");
            }
            
    	else
    	catch (TheException e)
            {
                System.out.println("" + e + " input: " + strInput);
            }
    
            System.out.println();
            System.out.println("Program Ending!");
    	}
        }
    }
    class TheException extends Exception
    {
    	public String toString()
    	{
    		return "Illegal";
    	}
    }

  11. #11
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Yes you can't use just a try or a catch. It's a simple idea pal.

    If you try to do something, there you have something to catch. Same for wiser versa.

  12. #12
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    I understand that YOU need some try/catch block, but unfortunately that piece of code doesn't need it ;) Can you tell me why you need the try/catch thing? Maybe we can come up with something.
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

Similar Threads

  1. try catch!?
    By Joe2003 in forum Advanced Java
    Replies: 2
    Last Post: 01-28-2008, 07:51 PM
  2. Try Catch
    By Renegade85 in forum New To Java
    Replies: 4
    Last Post: 12-03-2007, 04:10 PM
  3. when to use try...catch
    By javaplus in forum New To Java
    Replies: 2
    Last Post: 11-18-2007, 08:52 PM
  4. try...catch block
    By javaplus in forum New To Java
    Replies: 3
    Last Post: 11-06-2007, 07:53 PM
  5. Use try and catch
    By zoe in forum New To Java
    Replies: 2
    Last Post: 07-25-2007, 07:50 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •