I'm really wondering where to pick up the error.
If you try-catch in a subroutine, you may not reach the place you want to pick up.
java was the same
If the same Exception is thrown in a multi-stage subroutine, it can only be picked up in the inner subroutine.
public class MyException {
final private static int[] M = {1,2,3};
public static void main(String[] args) {
try {
subroutine(M);
}
catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("[SECOND] catch : " + e.getMessage());
}
}
public static void subroutine(int[] M) throws ArrayIndexOutOfBoundsException {
try {
System.out.println(M[4]);
}
catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("[FIRST] catch : " + e.getMessage());
}
}
}
result
[FIRST] catch : Index 4 out of bounds for length 3
If you throw it again in the inner catch, you can pick it up on the outside. When throwing, pass the argument e in a nice way. If it remains e, an error occurs. I'm not sure.
public class MyException {
final private static int[] M = {1,2,3};
public static void main(String[] args) {
try {
subroutine(M);
}
catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("[SECOND] catch : " + e.getMessage());
}
}
public static void subroutine(int[] M) throws ArrayIndexOutOfBoundsException {
try {
System.out.println(M[4]);
}
catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("[FIRST] catch : " + e.getMessage());
throw new ArrayIndexOutOfBoundsException(e.getMessage());
<---Throw
}
}
}
result
[FIRST] catch : Index 4 out of bounds for length 3
[SECOND] catch : Index 4 out of bounds for length 3
So what I mean is --It is easier to see where to pick up errors as much as possible ――But each module also has a role, so it is important to divide it within the scope of responsibility. --When delimiting, if you easily pick up Exception / RUntimeException, it will not reach the outside --You have to pick up a proper xxException as finely as possible inside. ――In order to do that, you need to know exactly what to do and what exception to come out. --If & throw is the best -(like if == 0: throw new DivededByZeroException)
reference http://math.hws.edu/javanotes/c8/s3.html
The last code here also consists of if + throw. I think I'm writing something like that, but I'm too sleepy to understand anymore, so I go to bed.
Well that kind of memo
Recommended Posts