Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to propagate an exception in java

I am a C programmer and just learning some java recently because I am developing one android application. Currently I am in a situation. Following is the one.

public Class ClassA{

public ClassA();

public void MyMethod(){

   try{
   //Some code here which can throw exceptions
   }
   catch(ExceptionType1 Excp1){
   //Here I want to show one alert Dialog box for the exception occured for the user.
   //but I am not able to show dialog in this context. So I want to propagate it
   //to the caller of this method.
   }
   catch(ExceptionType2 Excp2){
   //Here I want to show one alert Dialog box for the exception occured for the user.
   //but I am not able to show dialog in this context. So I want to propagate it
   //to the  caller of this method.
   }
   }
}

Now I wan to use call the method MyMethod() somewhere else in another class. If some one can provide me some code snippet how to propagate the exceptions to the caller of MyMethod() so that I can display them in a dialog box in the caller method.

Sorry If I am not so much clear and weird in the way of asking this question.

like image 671
Surjya Narayana Padhi Avatar asked Feb 29 '12 12:02

Surjya Narayana Padhi


2 Answers

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.

like image 61
Jon Skeet Avatar answered Oct 12 '22 00:10

Jon Skeet


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
    }
}
like image 33
user219882 Avatar answered Oct 12 '22 00:10

user219882