Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDE forces to surround with try/catch and not throw the exception

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.

like image 346
abhinavkulkarni Avatar asked Jul 27 '13 01:07

abhinavkulkarni


People also ask

Can we catch exception without throw?

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.

How do you handle exceptions in try catch?

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.

How do you handle exceptions without try and catch?

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 when an exception is thrown and not caught?

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.


1 Answers

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.

like image 189
rocketboy Avatar answered Nov 01 '22 00:11

rocketboy