Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is there any other solution ???

 
Rohan Kayan
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class error_test
{
public static void main(String[] args)
{
try
{
test1();
}
catch(Exception ex)
{
System.out.println("Exception is catched");
}
catch(Error temp)
{
System.out.println("Error is cathced");
}
}
public static void test1()
{
try
{
test2();
}
catch(Exception e)
{
}

}
public static void test2()
{
Error myError= new Error("Error by Rohan ");
throw myError;
}
}



Actually I want to throw an Error or Exception from test2 , which should not be caught by test1 . Is there any otherway to do this , except throwing an Error??
Throwing an error worth here or not , I am little bit confused about this .
So please guide me .
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you throw an Exception you will have to deal with it - either by catching the Exception or declaring that test1() throws Exception. If you throw an Error its different, and Error is kind of like a more serious RuntimeException, and it does not need caught. An Error is slightly confusing - it tends to be for an error which can end a process, but isn't condsidered serious enough to need explicitly caught at compile time. I think its a more useful class in a distributied, multiprocess environment than a desktop app, just from the point of view of how many Exceptions you may have to catch to do something simple. Throwing errors removes much of the exceptions handling code from an application, but still gives scope to signal something very serious has gone wrong. IMHO though - a RuntimeException does the same job.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are not required to catch the exception if you don't want to. Instead, you can declare that the test1() method throws the exception as well:

Ultimately, someone must catch this exception, though. Throwing Error or RuntimeException instead basically circumvents the whole exception handling mechanism and can ultimately cause your program to exit without informing the user. Typically this is not considered good behavior. I suggest that you read about the ideas behind exceptions and what is considered "proper" behavior when exceptional circumstances occur that can cause an exception.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic