try and catch

I have used so many times of the try--catch block in a java class. Now here are my questions:

1) Under what circumstancesshould the try{}catch{} block be used?

2) Under what circumstancesmust the try{}catch{} block be used?

3) What are the general rules (if any) for the catch Exception(any valid eception object will do)?

Thanks

Scott

[388 byte] By [scottjsna] at [2007-11-27 5:17:53]
# 1

Use it when you should, and when you must, you must!

Can you be more specific? One place where you must is in this situation:

void f() {

try {

g();

catch (IOException e) {

...

}

}

void g() throws IOException {...}

... since IOException is a checked exception that isn't propagated through f.

Of course, maybe a better solution would be to redo f to throws IOException

and have a higher method do the catching!

Hippolytea at 2007-7-12 10:40:51 > top of Java-index,Java Essentials,Java Programming...
# 2

> 1) Under what circumstances should the try{}catch{} block be used?

When the compiler complains about uncaught exceptions (and you don't want to throw them on).

> 2) Under what circumstances must the try{}catch{} block be used?

When the compiler complains about uncaught exceptions (and you can't throw them on).

> 3) What are the general rules (if any) for the catch Exception(any valid eception object will do)?

You must catch an Exception... unless you catch it as a Throwable. Or you at least have to have a catch for each specific exception type that is declared throwable in the code within the try block, or a common superclass of multiple exceptions (such as Exception).

bsampieria at 2007-7-12 10:40:51 > top of Java-index,Java Essentials,Java Programming...
# 3

Thanks for the help.

Let me try to readdress the issue, see if I really understand it.

1) try{}catch(TestException e){} block MUST preceded by a throw; no throw no catch?

2) If a function does NOT explicitly throw any Exception, still in try--catch block, the catch will capture an Exception object;

such as:

public void test(){

try{}

catch(Exception e){}

--Correct?

3)If an exception class is defined with a Throwable object in a constructor:

public class TestException extends RMSException {

public TestException(Throwable exception) {

super(exception);

}

THEN in a class:

public class testSession implements Filter {

public void doFilter(

ServletRequest req,

ServletResponse resp,

FilterChain chain)

throws ServletException, IOException {

//I can actually use

try{}

} catch (TestException e) {

e.printStackTrace();

even if I did not throw the TestException?

Thanks

Scott

scottjsna at 2007-7-12 10:40:51 > top of Java-index,Java Essentials,Java Programming...