Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception

 
Guru dhaasan
Ranch Hand
Posts: 126
Java Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anyone tell me what the paragragraph tries to convey : {From SCJp, Catthy sierra and Bert Bates book P:359 Para:6}

Suppose your method does not directly throw an exception, but calls a method that does. You can choose not to handle the exception yourself and instead just declare it, as though it were your method that actually throws the exception. If you do declare the exception that your method might get from another method, and you don�t provide a try/catch for it, then the method will propagate back to the method that called your method and either be caught there or continue on to be handled by a method further down the stack
 
David McCombs
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is saying that if an exception is never handled by a catch block the exception will keep propagating back until it is handled or propagates right out of your program(usually main) and crashes it.

public static void main(String[] args) throws MyException
{
...
thisMethod();

}

public static void thisMethod()throws MyException
{
thatMethod();

}

public static void thatMethod()throws MyException
{
anotherMethod();

}

public static void anotherMethod()throws MyException
{
...
throw new MyException(...);

}

Once anotherMethod throws the exception, control goes back to thatMethod(), but since no catch block exists, control goes to thisMethod(). Again no catch block, so control goes to main, and since it isn't handled it gets thrown again and the program crashes and a stack trace is printed.

Now, this example is a bit trite but I think it is more clear then if a uncaught exception were thrown(the throws statement would not be required). Now lets say that a try/catch were caught in thisMethod and everything else is the same:

public static void thisMethod()
{

try
{
thatMethod();
}
catch(MyException e)
{
//handle error
}
//more stuff happens or the method returns
}

Now, when the error is thrown in anotherMethod(), the exception gets thrown to thatMethod(), can't catch it so is thrown to thisMethod(), but this time a catch is included, so whatever code is needed to handle it is executed and as long as a System.exit(intVal) is not called that code after the block is executed. When the method returns from thisMethod() control goes back to main.

Hope this helps.
[ January 09, 2007: Message edited by: David McCombs ]
 
Guru dhaasan
Ranch Hand
Posts: 126
Java Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks David. This helped me a lot
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic