tags:

views:

427

answers:

4

hi all i have question regarding chain exception

try{ } catch(Exception e) { throw new SomeException(); }

if i do like this my eclipse will prompt error at line throw new SomeException(); stating "unhandled exception" and i must put something like

try{ } catch(Exception e) {
                            try{ throw new SomeException(); } catch(Exception e){} 
                           }

why must do like this because tutorial that i read .example http://java.sys-con.com/node/36579 , does not have to do this

+3  A: 

your method must declare that it may throw that exception. so, you must add:

throws SomeException {

at the end of your method's header.

cd1
So you don't need the try/catch since it does add any value anyway.
Peter Lawrey
the try/catch block is needed because he wants to catch any exception in the try block and throw SomeException instead.
cd1
+4  A: 

It depends if SomeException is a checked exception or not. If it is (it extends Exception but not RuntimeException) then you have to declare it on the method or throw a RuntimeException instead.

This is what your code should look like:

...) throws SomeException {
....
try {
 ....
} catch (Exception e) {
   throw new SomeException(e);
}

If some exception doesn't have a constructor which takes an exception, then do this:

throw (SomeException) new SomeException().initCause(e);

That way when the exception is ultimately caught, you know the root cause of the problem.

Yishai
syntax correction: new SomeException().initCause(e);
Chadwick
@Chadwick: Fixed, thanks.
Yishai
+6  A: 

You'll need to declare that the method throws another exception, if the exception is a checked exception.

("The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes." -- Java Language Specification, Second Edition, Section 11.2)

For example, rather than:

void someMethod {
    try {
        // Do something that raises an Exception.
    } catch (Exception e) {
        throw new SomeException();    // Compile error.
    }
}

A throws needs to be added to the method declaration:

void someMethod throws SomeException {
    try {
        // Do something that raises an Exception.
    } catch (Exception e) {
        throw new SomeException();    // No problem.
    }
}
coobird
+1  A: 

You need to add "throws SomeException" to your method declaration. You need to specify any exception types that your method throws except for exceptions that descend from RuntimeException.

Ted Elliott