Questions about rethrowing exceptions

J

Jon

Hello,

I am relatively new to the Java language and am working on a
communications API. This API will read and write to streams derived
from a socket. Naturally, there is the possibility that a socket
failure could occur. My API internally catches exceptions of type
IOException because this needs to change the state of my network
object. However, I also need to propogate the error back out to the
calling application. I am currently attempting to do so as shown
below:

try
{
...
}
catch(IOException e)
{
// do my own processing here
throw e;
}

My question is whether this is an appropriate use of exceptions and
whether it will have the intended consequences of propogating the
exception to the application?

Regards,

Jon Trauntvein
 
C

Christopher Benson-Manica

(I am not a guru, but...)
try
{
...
}
catch(IOException e)
{
// do my own processing here
throw e;
}
My question is whether this is an appropriate use of exceptions and
whether it will have the intended consequences of propogating the
exception to the application?

Yes, IME it's common to re-throw exceptions in this manner, and it
will do what you intend.
 
T

Thomas Fritsch

Jon said:
I am relatively new to the Java language and am working on a
communications API. This API will read and write to streams derived
from a socket. Naturally, there is the possibility that a socket
failure could occur. My API internally catches exceptions of type
IOException because this needs to change the state of my network
object. However, I also need to propogate the error back out to the
calling application. I am currently attempting to do so as shown
below:

try
{
...
}
catch(IOException e)
{
// do my own processing here
throw e;
}

My question is whether this is an appropriate use of exceptions and
whether it will have the intended consequences of propogating the
exception to the application?
Your approach is OK as long as your try/catch is inside a method which
is declared with "throws IOException".

Another approach (which is possible since Java 1.4) is to wrap the
caught IOException into your own Exception object like below:

void yourMethod(...) throws YourException
{
try
{
...
}
catch(IOException e)
{
// do my own processing here
YourException e2 = new YourException("...");
e2.initCause(e);
throw e2;
}
}

See also the API docs of Throwable#initCause and Throwable#printStackTrace.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,266
Messages
2,571,082
Members
48,773
Latest member
Kaybee

Latest Threads

Top