Christian Eric Paran
Christian Eric Paran

Reputation: 1010

Try Catching from another Method

Try Catch from another method:

method1(){
   try {

       method2();

   }catch(Exception e){


   }
}

 method2(){
    try{

       //ERROR FROM HERE

    }catch(Exception e){

    }

 }

How will method1() catch the error from method2()?

Upvotes: 3

Views: 1426

Answers (4)

sdasdadas
sdasdadas

Reputation: 25156

If you throw another exception in method2's catch block.

public void method2() {
    try {
        // ...
    } catch(Exception e) {
        throw new NullPointerException();
    }
}

Upvotes: 2

Jason
Jason

Reputation: 1309

    public void method1(){
        try {
            test2();
        } catch (IOException ex) {
            //catch test2() error
        }
    }

    public void method2() throws IOException{

    }

Use throws

Upvotes: 2

sp00m
sp00m

Reputation: 48837

It won't until you re-throw it within the catch block of your method2 by adding throw e;.

Upvotes: 0

Alex DiCarlo
Alex DiCarlo

Reputation: 4891

method1() will not catch the error, unless you re-throw it from the catch block in method2().

void method2() {
    try {
        // Error here
    } catch(Exception e) {
        throw e;
    }
}

Upvotes: 9

Related Questions