Forgive me if this is a stupid question, but as far as I know, all Java exceptions must be caught and handled. For example, something like this would create a compiler error:
public String foo(Object o) {
if (o instanceof Boolean) {
throw new Exception();
}
return o.toString();
}
Because the method foo()
didn't add a throws
clause.
However, this example would work (unless either the method foo()
didn't have a throws
clause or the method bar()
didn't surround usage of foo()
in a try/catch
block):
public String foo(Object o) throws Exception {
if (o instanceof Boolean) {
throw new Exception();
}
return o.toString();
}
public void bar(Object o) {
try {
String s = foo(o);
}
catch (Exception e) {
//...
}
//...
}
At the end, sometimes a Java program still sometimes crashes due to an unhandled exception.
How does this happen?