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.
You can avoid catching an exception, but if there is an exception thrown and you don't catch it your program will cease execution (crash). There is no way to ignore an exception. If your app doesn't need to do anything in response to a given exception, then you would simply catch it, and then do nothing.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.
What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With