Reputation: 2389
I understand the difference between checked and unchecked exceptions. Java compiler forces programmer to either surround the checked exception with a try/catch block or add a throw declaration in the method signature.
However sometimes I see that in Eclipse the compiler only gives me an option to surround the statement with a try/catch block and not throw it. Why is this so? Is this because in the inheritance hierarchy, the class (which contains code that potentially could produce an exception) is at the top?
As an example, I was writing a map function for a Hadopp
mapper:
public void map(BytesWritable key, Text value, Context context) {
String[] fields = value.toString().split("\t");
String referrer = fields[10];
context.write(new LongWritable(referrer.length()), new Text(
referrer));
}
It's a very simple map function, I am extracting a field from a row and emitting it's length as a key and itself as a value. Now, I get an error Unhandled exception type InterruptedException
that Context.write()
throws and Eclipse only gives me an option to surround it by a try/catch block and not throw it upwards in the hierarchy. Why is this so?
For a reference you can read the function signature of Context.write
here.
Thanks.
Upvotes: 6
Views: 3068
Reputation: 9741
throws
is a part of method signature. If you are defining an abstract method, you must adhere to its signature. You can't add the throws
while implementing it.
Upvotes: 2
Reputation: 81151
If one is overriding a method which is not declared as throwing a particular checked exception, and one is calling a method which is declared as throwing a checked exception which one expects to handle, one should catch that exception, handle it, and not rethrow it. If one is not expecting any circumstance to arise where the called method would actually throw the indicated checked exception, one should catch that exception, wrap it in some type derived from RuntimeException
, and throw that. Some people advocate an empty catch statement, but I regard that as an anti-pattern. If a method is expected never to throw a certain exception, but it does so anyway, that pretty much implies that some condition exists which the programmer hasn't considered and isn't prepared to handle. If the exception is silently swallowed the program might blindly stumble into doing the right thing, but there's no reason to expect proper behavior after an unanticipated exception.
Upvotes: 0