I know that try
statement is useless without catch
or finally
, and the finally
clause is optional in a try-catch
block. However, when I write a try
statement without catch
or finally
, the compiler suggests inserting finally
clause to complete try statement.
For example:
try {
for (int j = 0; j <= i.length; j++) {
System.out.println(i[j]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Catch");
} //no errors
try {
for (int j = 0; j <= i.length; j++) {
System.out.println(i[j]);
}
} //syntax error
Error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "Finally" to complete TryStatement
at Driver.main(Driver.java:12)
Why is finally
the only recommended statement to implement? Why not catch
?
"I might want something to happen despite an exception being thrown, so I may not be looking to handle a specific exception in a specific way, but I may want to ensure that at least SOMETHING generic happens. If I can't handle it, at least do something." Looking for somebody to confirm on this.