I'm sure I'm going to catch flack for this... but I'm coming from a language with no try
/catch
blocks and I'm learning about Java exception catching, and I'm having a hard time seeing how it's not just a lazy version of validation. I've seen a few examples like:
String Box [] = {"Book", "Pen", "Pencil"};
while(i<4)
{
try
{
System.out.println(Box[i]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Subscript Problem " + e);
i++;
}
and:
int y = 0;
int x = 1;
// try block to "SEE" if an exception occurs
try
{
int z = x/y;
System.out.println("after division");
}
catch (ArithmeticException ae)
{
System.out.println(" attempt to divide by 0");
}
These are obviously very rudimentary examples... but IMO either these are terrible examples of catching errors, or there's no good reason to do it. In example one if we loop for number of elements in Box
we don't need to check for out of bounds indexing. In example two if we check for a divisor of 0, we don't need to check for that ArithmeticException
.
Is there a good example or reason why using try
/catch
blocks is better than just good-old-fashion variable validation? or is it just the "Java" way?