How to propagate an exception in java

自古美人都是妖i 提交于 2019-11-29 09:44:19

Just don't catch the exception in the first place, and change your method declaration so that it can propagate them:

public void myMethod() throws ExceptionType1, ExceptionType2 {
    // Some code here which can throw exceptions
}

If you need to take some action and then propagate, you can rethrow it:

public void myMethod() throws ExceptionType1, ExceptionType2 {
    try {
        // Some code here which can throw exceptions
    } catch (ExceptionType1 e) {
        log(e);
        throw e;
    }
}

Here ExceptionType2 isn't caught at all - it'll just propagate up automatically. ExceptionType1 is caught, logged, and then rethrown.

It's not a good idea to have catch blocks which just rethrow an exception - unless there's some subtle reason (e.g. to prevent a more general catch block from handling it) you should normally just remove the catch block instead.

Don't catch it and rethrow again. Just do this and catch it in the place you want

public void myMethod() throws ExceptionType1, ExceptionType2 {
    // other code
}

Example

public void someMethod() {
    try {
        myMethod();
    } catch (ExceptionType1 ex) {
        // show your dialog
    } catch (ExceptionType2 ex) {
        // show your dialog
    }
}

Just rethrow the exception

throw Excp1;

You will need to add the exception type to the MyMthod() declaration like this

public void MyMethod() throws ExceptionType1, ExceptionType2  {

   try{
   //Some code here which can throw exceptions
   }
   catch(ExceptionType1 Excp1){
       throw Excp1;
   }
   catch(ExceptionType2 Excp2){
       throw Excp2;
   }
}

Or just omit the try at all since you are no longer handling the exceptions, unless you put some extra code in the catch statements doing things with the exception before rethrowing it.

MohWaylie

I always do it like this :

public void MyMethod() throws Exception
{
    //code here
    if(something is wrong)
        throw new Exception("Something wrong");
}

then when you call the function

try{
    MyMethod();
   }catch(Exception e){
    System.out.println(e.getMessage());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!