This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
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

Can Java catch more than one exceptions from the single try_catch block?

 
Mark Lau
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can Java catch more than one exceptions from the single try-catch block? Suppose I have the following code:

try
{ method1();
method2();
method3();
}
catch(ArithmeticException ae)
{ }

And suppose method1(), method2(), method3() all throw (instead of *might* throw) ArithmeticException, Is Java able to catch all 3 exceptions?
I tried a code, it does not catch all 3 exceptions. Could only catch the exception thrown by the 1st method.
Please confirm me, thanks a lot.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If method1()throws an exception, your program will immediately go to the catch block. method2() will not have a chance to throw anything.
-anthony
 
Sal Velinus
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could put method2 in a finally block and it will execute (or throw an exception). At least that's what I read earlier today.
 
smart andy
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i agree.
 
Chinmay Bajikar
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suppose u will have to write 3 catch blocks for 3 diffrent expressions.
Otherwise,u write a catch blk with the father of
all exceptions as the argument.
catch (Exception e)
{
}
though i know
both ways it is not convincing answer enough.
thankz,
Chinmay
 
Chinmay Bajikar
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok
im sorry for that prev reply.
I did not read the question properly.
If all the 3 methods throw same exception then
the method which throws first will be caught and
control transferred to the catch blk.
JVM wont go on to evaluate the next method.
Sorry again.
I thought what if all the methods throw diff exceptions and u need to catch them.
.....Chinmay
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic