• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
Samy Ganou
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method like this:

public voide methodA(){

try {
.........

} catch (ExceptionA a){
try{
doSomethingB();
}catch(ExceptionB b){
throw new ExceptionB(b)

}

}

The problem is that when an exception occur on doSomthingB() original stack trace will be lost. No chance to have information about exceptionA.

An idea ?
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is because you are dealing with the two possible exceptions differently. You might use a single try block with two catch blocks, for ExceptionA and ExceptionB. And why are you throwing an Exception of the same type as you are catching? That looks very peculiar.
 
Samy Ganou
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:That is because you are dealing with the two possible exceptions differently. You might use a single try block with two catch blocks, for ExceptionA and ExceptionB. And why are you throwing an Exception of the same type as you are catching? That looks very peculiar.


I can not make one try , because i want to call the method doSomethingB() only when an ExceptionA occurs.

I made an error , so i throw ExceptionD() on the second catch.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not exactly sure what you're trying to do, but you still have access to the original exception inside the second exception handler because of normal Java scoping rules. If you need access to it internally then either throw a new exception and chain the original, or provide an exception B constructor that takes an exception A as a parameter.
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

As David suggests, both exceptions 'aa' and 'bb' are available
within the seond catch block. You should consider using code
indents as it shows parameter scope very clearly.

Jim ... ...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic