Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Nested try/catch problem

Status
Not open for further replies.

4345487

Programmer
Dec 31, 2002
132
US

Hi,

I have a problem with a nested try/catch error handler in the example below if there is an error
in validatefld it works OK it goes to the fieldvalidation catch and returns to where the test()
method was call but if the error occurs on step one method it goes to the exception catch and
sets the error code to 80 and the message but then it executes steptwo() and stepthree() methods
before returning to where the method test() was call from and it displays the error message
how can I return to test() if an error occurs in stepone() with out executing
steptwo() and stepthree()

test()
{
try
{

validatefld();
try
{
stepone();
}
catch(exception e)
{
errorcdoe = 80;
errorMsg = "this is a tes")
}

steptwo();
stepthree();

}
catch(fieldvalidation ex)
{
errorcdoe = 10;
errorMsg = "field validation error")

}
catch(test ez)
{

}
carch(exception e)
{
}
}
 
Rather than setting an error message, try throwing an exception instead.

Replace

errorMsg = "this is a tes")

with

throw new Exception("this is a tes");
 
Basically this is kinda wrong, you should do this really:

Code:
try{

... code ..

}catch(exception e)
    if(e instanceof test)
        ... do something ...
    ... other tests on the exception to find out what it is...
}

You should never need to nest exception handling.

M

 
Nested exception handling is expensive to say the least. Just think about all the transaction rollbacks !

Saying that it is never necessary is a little harsh - sometimes it is needed (especially using JDBC).

However, in this OP's example, it is just unnecessary. Try to simplify things, and either return from a method if it fails, or throw an exception.

--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top