Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception already caught error

Here's the code:

public class Exc {
int x = 2;
public void throwE(int p) throws Excp, Excp2 { 
    if(x==p) {
        throw new Excp();
    }
    else if(x==(p+2)) {
        throw new Excp2();
    }
  }
}

Here's the handler code:

public class tdExc {
public static void main(String[] args) {
    Exc testObj = new Exc();
    try {
        testObj.throwE(0);
        System.out.println("This will never be printed, so sad...");
    } catch(Exception Excp) {
        System.out.println("Caught ya!");
    } catch(Exception Excp2) {
        System.out.println("Caught ya! Again!!!!");
    } finally {
        System.out.println("This will always be printed!");
    }
  }
}

Excp and Excp2 both extends Exception and have similar code(nothing). Now I'm getting the error Exception has already been caught error at Excp2, regardless of whether I supply 2 or 0 to throwE method.

like image 490
DM_Morpheus Avatar asked Dec 16 '22 23:12

DM_Morpheus


1 Answers

You're looking for:

try
{ }
catch(Excp excp)
{
   log(excp);
}
catch(Excp2 excp2)
{
   log(excp2);
}
finally
{ }

When you catch an exception, to specify the type of the exception, and the name of of its reference.
Your original code tried to catch Exception, which is the least specific exception, so you cannot catch anything after that.

like image 177
Kobi Avatar answered Dec 19 '22 14:12

Kobi