Results 1 to 11 of 11
  1. #1
    arefeh is offline Member
    Join Date
    Dec 2009
    Posts
    76
    Rep Power
    0

    Default different exceptions and behavior of try-catch

    Java Code:
    class NestedTry3
    {
    public static void main (String args[])throws Exception
      {
      		try 
      		{
      			throw new ArithmeticException();
          } 
          catch (ArrayIndexOutOfBoundsException the) 
          {
            System.out.println("ArrayIndexOutOfBoundsException");
          } 
      }
    }
    output:
    Exception in thread “main” in java.lang.ArithmeticException
    At NestedTry3.main(NestedTry3.java:30)


    Java Code:
    class TemperatureException extends Exception 
    {
    }
    
    class TooColdException extends TemperatureException 
    {
    }
    
    class TooHotException extends TemperatureException 
    {
    }
    
    class NestedTry3
    {
    public static void main (String args[])throws Exception
      {
      		try 
      		{
      			throw new TooHotException();
          } 
          catch (TooColdException the) 
          {
            System.out.println("TooColdException");
          } 
      }
    }
    Error in time of compiling:Exception TooColdException never thrown in the body of corresponding try statement.

    Question: why this error occur?
    In both programs I threw an exception and want to handle another exception in catch clause.
    In the first program, ArithmeticException and ArrayIndexOutOfBoundsException are defined exceptions in java.
    But TooHotException and TooColdException are defined by user.
    ArithmeticException is subclass of RuntimeException and ArrayIndexOutOfBoundsException is subclass of IndexOutOfBoundsException.
    Also, TooHotException and TooColdException are subclasses of TemperatureException.

    I think these programs are the same behavior. Then why these behave differently?

  2. #2
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    The difference is that in the first example, you catch an exception that extends RuntimeException, whereas in the second it doesn't (it only extends Exception). If TooColdException were to extend RuntimeException, then no error occurs (like in the first case).

    If TooColdException were a RuntimeException, it could be thrown and caught during Runtime. However, if it's not a RuntimeException, you must explicitly catch it (and can only catch it if it's possible to be thrown). In your code, a TooColdException could never be thrown, so an error occurs (because it's an Exception, not a RuntimeException).

    In short, if it were a RuntimeException, the compiler couldn't care less that you catch it.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  3. #3
    arefeh is offline Member
    Join Date
    Dec 2009
    Posts
    76
    Rep Power
    0

    Default

    Hello
    I used from two subclasses of Exception class in this program:
    Java Code:
    class NestedTry3
    {
    public static void main (String args[])throws Exception
      {
         try 
         {
             throw new IOException();
          } 
          catch (IllegalAccessException the) 
          {
            System.out.println("IllegalAccessException");
          } 
      }
    }
    and I got Error in time of compiling:Exception IllegalAccessException never thrown in the body of corresponding try statement.

    Thank you very much. It was wonderful.

    If TooColdException were a RuntimeException, it could be thrown and caught during Runtime.
    that is, all subclasses of RuntimeException are thrown in run time?

  4. #4
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    Quote Originally Posted by arefeh View Post
    that is, all subclasses of RuntimeException are thrown in run time?
    Well, both are thrown at run time, but a RuntimeException doesn't need to be declared or caught, whereas a non-RuntimeException must be declared (or caught).

    That's why the code using RuntimeExceptions (an "unchecked" exception) is fine - because RuntimeExceptions don't need to be declared. A non-RuntimeException (a "checked" exception) must be explicitly caught or explicitly thrown (an error occurs if you don't, or do when you shouldn't - like in your case).


    I would suggest reading up on them in the Java tutorials - Exceptions. Specifically, check out Unchecked Exceptions — The Controversy to read more about when/why to use RuntimeException ("unchecked") versus a normal Exception ("checked").
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  5. #5
    arefeh is offline Member
    Join Date
    Dec 2009
    Posts
    76
    Rep Power
    0

    Default

    Hello
    Thank you. I read these links.
    Well, both are thrown at run time, but a RuntimeException doesn't need to be declared or caught, whereas a non-RuntimeException must be declared (or caught).
    that is, it is not necessary that we use from catch clause for catching RuntimeException exceptions? That is, we allow the stack trace prints stack?

    Please see following program:

    Java Code:
    class TemperatureException extends Exception 
    {
    }
    
    class TooColdException extends TemperatureException 
    {
    }
    
    class TooHotException extends TemperatureException 
    {
    }
    
    class NestedTry3
    {
    	static void test(int HC)throws TemperatureException
    	{
    		if(HC>0)
    		{
    			throw new TooHotException();
    		}
    		else
    		{
    			throw new TooColdException();
    		}
    	}
    public static void main (String args[])throws TemperatureException
      {
          try 
         {
      	test(5);
          } 
          catch (TooHotException the) 
          {
            System.out.println("TooHotException");
          } 
          catch(TooColdException tce) 
          {
        	  System.out.println("TooColdException");
          }      
      }
    }
    output is: TooHotException

    that is, Actually TooColdException and TooHotException are thrown in static void test(int HC) method or one of them is thrown?

    I asked this question because no error occurred in time of compiling such as:
    Exception TooColdException never thrown in the body of corresponding try statement.

  6. #6
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    For RuntimeExceptions, the compiler doesn't really care what you do. You can catch them or you can choose not to. You can throw them and not catch them or you can catch ones that are not thrown.

    For non-RuntimeExceptions, the compiler will be very picky. First, you must catch them, or declare them as thrown (as part of the method signature, like you did). Also, you cannot catch one that isn't possible to be thrown. The "possible" ones are the ones that are declared to be thrown by the method(s) in your try block - in your code a TemperatureException.



    Quote Originally Posted by arefeh View Post
    that is, Actually TooColdException and TooHotException are thrown in static void test(int HC) method or one of them is thrown?

    I asked this question because no error occurred in time of compiling such as:
    Exception TooColdException never thrown in the body of corresponding try statement.
    Both are possible to be thrown, but only one can be thrown when you run the program. Like the code says, "if(HC>0) throw new TooHotException(); else, throw new TooColdException();". In other words, depending on the value of HC an exception is thrown, but only one is thrown.

    The reason no error occurs is because your main method throws TemperatureException (which is the same exception your method throws). If you wanted, you don't even need a try/catch block at all, because you declared that the main method throws the exception. If you were to remove the "throws TemperatureException" from main, you WOULD get a compile error, but a different one. It would complain because you test method throws a TemperatureException, which is never caught. For example, there could be a third exception (WayTooHotException) which is also a TemperatureException. Even though your main method would catch the other two, it wouldn't catch this one.

    In other words, you catch blocks have no effect on your code compiling or not (you could easily remove them). It is the fact that main throws TemperatureException that allows your code to run. Otherwise, you would need to catch a TemperatureException. Remember, just because these are the only two that CURRENTLY extend TemperatureException, doesn't mean that they will always be the only two. The Java compiler ensures your code works by making sure you catch the exception that you declared that is thrown (TemperatureException) - it really doesn't care if you catch the exceptions that extend it.
    Last edited by CodesAway; 02-05-2010 at 05:20 AM.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  7. #7
    arefeh is offline Member
    Join Date
    Dec 2009
    Posts
    76
    Rep Power
    0

    Default

    Hello
    Really I thank you. Your guidance about non-RuntimeExceptions was very good for me.

    For RuntimeExceptions, the compiler doesn't really care what you do. You can catch them or you can choose not to. You can throw them and not catch them or you can catch ones that are not thrown.
    Java Code:
    class NestedTry3
    {
    	public static void main (String args[])
      {
      	int a=10,b=0,c;
      		try 
      		{
      			c=a/b;
          } 
          finally
          {
          } 
      }
    }
    output is stack trace


    Java Code:
    class NestedTry3
    {
    	public static void main (String args[])
      {
      	int a=10,b=0,c;
      		try 
      		{
      			c=a/b;
          } 
          catch (ArithmeticException the) 
          {
            System.out.println("ArithmeticException");
          }
          finally
          {
          } 
      }
    }
    output is ArithmeticException

    Question: really it does not differ that we do not get stack trace and our program completes normally? It does not differ for compiler but it should differ for us. Ok?

  8. #8
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    Quote Originally Posted by arefeh View Post
    Question: really it does not differ that we do not get stack trace and our program completes normally? It does not differ for compiler but it should differ for us. Ok?
    The stack trace means the program didn't finish naturally - there was an error. In other words, the program will just stop at the error.

    However, you don't want your program to just stop due to an error. Instead, usually you want to do something. In your example, you would usually want to catch the exception, output to the user a message like "The value for 'b' cannot be 0." Then, the user can fix their mistake and the code continues as it should.

    Edit:
    Sorry for the confusion. I should have explained that I met exclusively that "the compiler doesn't really care what you do". Of course, your user REALLY cares - they don't want the program to stop running. For example, an ArithmeticException is thrown if you divide by zero. Well, for this, you can always check before doing the operation that the value is non-zero (which is the preferred way). If the value were zero, you would usually inform the user that they must enter a value which is not zero; then, ask for a new value.

    Java Code:
    class NestedTry3
    {
    	public static void main(String args[])
    	{
    		int a = 10, b = 0, c;
    
    		if (b == 0) {
    			System.out.println("The value for 'b' must be non-zero.");
    			return;
    		}
    
    		c = a / b;
    	}
    }
    Last edited by CodesAway; 02-06-2010 at 02:05 AM.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  9. #9
    arefeh is offline Member
    Join Date
    Dec 2009
    Posts
    76
    Rep Power
    0

    Default

    Hello
    you would usually inform the user that they must enter a value which is not zero; then, ask for a new value.
    Ok. That is all right.

    Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. From:Unchecked Exceptions — The Controversy (The Java™ Tutorials > Essential Classes > Exceptions)
    Then, it can result that our attention to probable errors in our program can free us from using RuntimeExceptions. OK?
    That is, with putting following code in our program, we feel safety and we do not need to use from try-catch for catching and handling RuntimeExceptions .OK?
    Java Code:
    		if (b == 0) {
    			System.out.println("The value for 'b' must be non-zero.");
    			return;
    		}

    If I am not right, then following code is good?

    Java Code:
    class DiveByZero
    {
    	public static void main(String args[])
    	{
    		int a = 10, b = 1, c;
    
    		if (b == 0) 
    		{
    			System.out.println("The value for 'b' must be non-zero.");
    			return;
    		}
    		
    		try
    		{
    			c = a / b;
    			System.out.println("c i= "+c);
    		}
    		catch(ArithmeticException e)
    		{
    			System.out.println("ArithmeticException");
    		}
    	}
    }

  10. #10
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    Quote Originally Posted by arefeh View Post
    Then, it can result that our attention to probable errors in our program can free us from using RuntimeExceptions. OK?
    That is, with putting following code in our program, we feel safety and we do not need to use from try-catch for catching and handling RuntimeExceptions .OK?
    Java Code:
    		if (b == 0) {
    			System.out.println("The value for 'b' must be non-zero.");
    			return;
    		}
    Correct. There may be exceptions to this rule, but in general, you shouldn't use try-catch blocks for runtime exceptions; rather, you should add code that checks the necessary conditions.

    For example, an ArithmeticException is thrown if you try to divide by zero. So, add checks to your code to ensure that you never divide by zero. An IndexOutOfBoundsException is thrown if you were to, for example, call array[5] on an array of size 2. To prevent this, ensure that your index is always between 0 (inclusive) and the size of the array (exclusive).


    On the other hand, non-runtime exceptions, like IOException, can result from actions outside of your control. For example, if you were to retrieve the contents from the clipboard (e.g. clipboard.getData(DataFlavor)), the method throws an IOException if it cannot retrieve the contents from the clipboard. This sort of error you cannot prevent (even with code checks).

    Some IOExceptions can be minimized (e.g. FileNotFoundException) by testing for the necessary conditions (in this case, check if the file exists - file.exists()). However, as the docs mention, this exception can also be thrown when the file exists, but cannot be accessed. For this reason, a FileNotFoundException is still a non-runtime exception, since there are cases that the exception can be thrown even if your code is perfect.


    In general, a RuntimeException is preventable by adding code checks to ensure that all conditions are met (e.g. testing for null to prevent a NullPointerException). A non-runtime exception is not preventable. It may be possible to minimize it's occurrence (e.g. testing if a file exists in the case of a FileNotFoundException). However, a non-runtime exception (even with proper code checks added) can still occur without anything being wrong in your code - this is why Java demands that we declare or catch the exception.
    Last edited by CodesAway; 02-06-2010 at 05:32 PM.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  11. #11
    arefeh is offline Member
    Join Date
    Dec 2009
    Posts
    76
    Rep Power
    0

    Default

    Thank you very much dear CodesAway.
    I studied many things about exceptions from you. I hope that I study more things about java in future from you.

Similar Threads

  1. Java Crossplatform Behavior
    By wdavis in forum New To Java
    Replies: 2
    Last Post: 11-05-2009, 01:22 PM
  2. htmlparser inconsistent behavior
    By sjchase in forum Advanced Java
    Replies: 0
    Last Post: 07-21-2009, 11:07 PM
  3. Strange behavior with Thread.sleep()
    By Steve11235 in forum Advanced Java
    Replies: 16
    Last Post: 05-04-2009, 05:24 AM
  4. strange refreshing behavior
    By diggitydoggz in forum New To Java
    Replies: 4
    Last Post: 12-27-2008, 04:51 PM
  5. how to catch two exceptions in one catch()?
    By arnab321 in forum New To Java
    Replies: 1
    Last Post: 11-06-2008, 10:54 AM

Posting Permissions

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