Because the x.substring(0,200)
throws a StringIndexOutOfBoundsException not a TryCatchException1.
If things worked the way you thought then when people do this:
try {
} catch (NumberFormatException e) {
} catch (SQLException e) {
} catch (Exception e) {
}
Then the other exceptions will never be caught and everything would go to the last Exception. It is true that you extend the StringIndexOutOfBoundsException, but that method doesn't throw the TryCatchException1.
Look at this:
public void methTryCatch() throws TryCatchException1 {
throw new TryCatchException1("TryCatchException1");
}
public void methOutOfBounds() throws StringIndexOutOfBoundsException {
throw new StringIndexOutOfBoundsException("StringIndexOutOfBoundsException");
}
main() {
try {
methTryCatch();
} catch (TryCatchException1 e) {
System.out.println("methTryCatch: "+e.getMessage());
} catch (StringIndexOutOfBoundsException e) {
System.out.println("methTryCatch: "+e.getMessage());
}
try {
methOutOfBounds();
} catch (TryCatchException1 e) {
System.out.println("methOutOfBounds: "+e.getMessage());
} catch (StringIndexOutOfBoundsException e) {
System.out.println("methOutOfBounds: "+e.getMessage());
}
try {
methTryCatch();
} catch (StringIndexOutOfBoundsException e) {
System.out.println("methTryCatch: "+e.getMessage());
}
}
Also since your method throws a TryCatchException1 you can do this:
public static void MyNumber(String x) throws TryCatchException1{
try{
String y = x.substring(0,200);
} catch(java.lang.StringIndexOutOfBoundsException e){
throw new TryCatchException1(e.getMessage());
}
}
OR
public static void MyNumber(String x) throws TryCatchException1{
String y = x.substring(0,200);
}
Try catching the above like this and see what happens:
try{
MyNumber("myStirng");
}catch(TryCatchException1 e){
System.out.println("BBBBB: "+e.getMessage());
}catch(java.lang.StringIndexOutOfBoundsException e){
System.out.println("AAAAAAA: "+e.getMessage());
}