开发者

Throw error to calling method!

I have a thread class and in the run method I am making a call to a web service, this call is in a try catch

try {
    // Make webs service call
}
catch (Ex开发者_JS百科ception e) {
    throw e;
}

Eclipse doesn't like this!

Basically I want to throw this error to the calling method and deal with it there?


If you throw a checked exception, the exception must be handled either with try/catch or declaring it as thrown in the method signature. See the exceptions tutorial; particularly the part about The Three Kinds of Exceptions.


Yep java.lang.Exception is checked, so you can't throw it (as Runnable.run does not declare any Exceptions in its throws clause; it doesn't have a throws clause). You could only throw RunTimeExceptions. You'll have to handle the Checked Exceptions - that's what Java is forcing you to do. One approach is to convert the Checked Exception into a RunTimeException so you can throw it. But don't forget this is a separate thread, so watch your handling logic.

public class ThreadFun implements Runnable {

    public void run()  {

        // LEGAL
        try {

        } catch (RuntimeException e) {
            throw e;
        }

        // NOT LEGAL
        try {

        } catch (Exception e) {
            throw e;
        }           
    }
}


That is because you are overriding run() and overriding won't allow you to declare broader exception to be thrown. You can wrap it up in RuntimeException.

Do it something like

 new Thread(new Runnable() {

            public void run() {
                try{
                   //your code
                }catch(Exception ex){
                    throw new RuntimeException(ex);//or appropriate RuntimeException
                }
            }
        }).start();

    }


Instead of catching the exception, add throws Exception to the method signature. This will force the calling method to catch the exception instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜