I have the following piece of code. I would like to know what sort of exceptions would be caught inside the catch block in a multithreaded enviorment.
class Goo
{
private Vector objects = new Vector();
public void kempute ()
{
Iterator iter = objects.iterator();
while (iter.hasNext()) {
try {
Object o = (Object)iter.next();
System.out.println(o.hashCode());
}
catch (Exception ex) {
//
}
}
}
public void addme (Object o)
{
objects.add(o);
}
}
I really couldnt find any exceptions. Any help is really appreciated.
An exception could be caught at that point if
or
throw an unchecked exception. Here are a couple of possibilities:
If you had previously called
addObject(null), a call toupdate()would lead to a NullPointerException when it callshashCode()on anullreference.If you have an instance of
Fooshared by two threads, and one callsaddObjectwhile the other is callingcompute(), then you could get aConcurrentModificationException.If
Vectorwas a custom class and notjava.util.Vector, theniter.next()could throw some other unchecked exception … at the whim of the author of said custom class. (OK … unlikely in the light of the OP’s comments.)(From aix’s answer) –
o.hashCode()could in theory throw any unchecked exception, depending on howo‘s class implements thehashCode()method.There may be other possibilities too.
If you are merely curious as to what the possible exceptions might be, the above more or less covers it.
If you want to tidy up this code, then it is probably a bad thing to be catching
Exceptionat that point. Each of those cases listed is a sign of a bug here or elsewhere in the application. Rather that catching the exception at that point and (presumably) trying to “make good” the problem, it is better to bomb out with a stacktrace, and then go back and fix the root problem that was being hidden by the catch.