Change unhandled exception auto-generated catch code in Eclipse? - java

If I have unhandled exception in Java, Eclipse proposes two options to me: (1) add throws declaration and (2) surround with try/catch.
If I choose (2) it adds a code
try {
myfunction();
} catch (MyUnhandledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I want to change this to
try {
myfunction();
} catch (MyUnhandledException e) {
throw new RuntimeException(e);
}
Is this possible?
UPDATE
Why are so love to change the topic people???
If exception is catched and printed it is also no need to catch it anymore. I like my application to crash if I forget to handle an exception by mistake. So, I like to rethrow it by default.

Yes, you can change the default code added by Eclipse.
In Preferences, navigate to Java>Code Style>Code Templates.
Under Code, select Catch block body.
Press the Edit button to change the code. When finished, press the
OK button.
Consider adding a TODO comment in the default catch block. For example, the default includes:
// ${todo} Auto-generated catch block

Personally, I use a generic idiom irrespective of the actual checked exception type, you might make Eclipse use that as a template instead:
try {
...
}
catch (RuntimeException e) { throw e; }
catch (Exception e) { throw new RuntimeException(e); }
The point is to wrap the whole code block instead of individually each line that may throw an exception. The block may throw any number of checked and unchecked exceptions, and this will allow the unchecked exceptions to pass through unharmed, and the checked exceptions will be wrapped.

If you are re-throwing your exception from the catch clause, then you would have to handle in the method that invoked your current method. But if you wrap your exception in RuntimeException, you won't need to handle it. But why would you do that?
I mean why not just: -
try {
myfunction();
} catch (MyUnhandledException e) {
throw e;
}
Because, in your code, basically you are wrapping a might be checked exception in an unchecked one. If I assume your MyUnhandledException as checked exception.
And also note that, if you are following this approach, you would still need to declare it to be thrown in your throws clause.
If you just want to do the way you are doing, then also it will work fine. You can change the Eclipse setting as per #Andy's answer.
But, it would be better to look at your design. Why is the method overrided throwing an exception not declared in your overriden method. Probably there is something wrong, that should be corrected.

You're probably aware of this... but if you want to get rid of all pesky clutter and irritations from checked exceptions, why not just add throws Exception to every single method?
In the case of an overridden interface method this sort of pattern could then be used:
#Override
public void close() throws IOException {
try {
_close();
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
private void _close() throws Exception {
// ... closing ops
}

Related

How to propagate exception from an overridden method in Java

What is the best practice to terminate the execution of an overridden method?
Here is the example code that explains the context:
#Override
protected String doInBackground(String... params) {
URL serverURL = null;
try {
serverURL = new URL((urlString));
} catch (MalformedURLException e) {
e.printStackTrace();
}
...
...
return response.toJSONString();
}
In the above code snippet, I am forced to catch MalformedURLException, so I used the try catch block. If that exception occurs, I would like to skip all the code below the catch block and propagate either the same exception or a different one that I would throw within the catch block until all the way to the Main method, hopping through the catch blocks and skipping the code in the middle in all the calling methods. How to do this?
The problems are:
1) I cannot add throws clause to the method signature because it is overridden and the base class doesn't allow it.
2) Since the method has to return a String, I have to specify the return statement after the catch block.(What do I return if an exception has occurred?)
3) Use System.exit in catch block - As some other posts on this forum point out, that may not be a good practice when you want your code to be reusable.
The best practice for such a case would be to wrap the MalformedURLException with a RuntimeException:
catch (MalformedURLException ex) {
throw new RuntimeException("Failed constructing URL", ex);
}
Ideally, you'd really like to edit the method's throws clause so it can accommodate any exceptions that are likely to stem from overrides; but since this is impossible in your case (as per your conditions), the above seems most reasonable to me.
A related best-practice would be to avoid logging the exception before wrapping it. From a design perspective, there's no need to do so — the caller already has access to the original Exception object (through the getCause() method of the thrown RuntimeException) so the caller should decide whether to log it or not.

check condition using try and catch block-java

I understand the basic try-catch, where we put methods that could possibly throw exceptions in the try block. But when we need to check if something is wrong, and throw an exception, is it correct to use the code below? And the exception is caught, the program will continue to execute?
I can't tell why the try is needed here, but without it eclipse says 'syntax error'. Thanks for your help in advance!
public run (){
if (something !=true) {
try{
throw new Exception();
}catch (Exception e){
}
Yes that is correct. You have to use try since that is where the exception-throwing code is entered and where exceptions are caught (just using a catch block won't serve any purpose)
Generally speaking, exceptions are used to let the calling code handle errors in your method.
If you just want to handle the error in run, you don't need exceptions:
public void run() {
if (something != true) {
// handle it
}
}
If you want the calling code to handle the error instead, this is where you need exceptions:
public void run() throws Exception {
if (something != true) {
throw new Exception();
}
}
And where you call run, use a try/catch block:
try {
run();
} catch (Exception e) {
// handle it
}
It is also recommended that you don't throw an Exception instance, use a custom subclass instead.

Is it useful to declare parent and child exceptions in the same throws clause?

I know that the code below does make sense:
try { ... }
catch (FileNotFoundException exc) { ... }
catch (IOException exc) { ... }
But does declaring those parent and child exceptions in the throws clause make sense?
Suppose I have the following code:
public void doSomething() throws FileNotFoundException, IOException { ... }
We all know that FileNotFoundException is a subclass of IOException. Now does it make sense in any way (readability, performance, et cetera) to declare it like that, opposing to just this:
public void doSomething() throws IOException { ... }
For the Java compiler, it doesn't matter whether a subclass is in the throws clause, because the superclass exception will cover it.
However, for documentation purposes it is important. The caller of your method may want to know that it can throw a subclass exception, e.g. FileNotFoundException, and handle it differently.
try {
doSomething();
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
}
catch (IOException e) {
System.out.println("An I/O error has occurred: " + e.getMessage());
}
Sometimes it makes sense to catch both exceptions, as long the the sub-class exception is specified first (otherwise, I think it won't even compile). It allows you to handle specific exceptions you care about in a different way than more general exceptions.
For example, I have code that reads from a socket. It's a blocking read, an I set a timeout, since there might be nothing to read. That's why I catch SocketTimeoutException and do nothing about it. If, on the other hand, I get other IOExceptions (IOException being an indirect super-class of SocketTimeoutException), I am throwing an exception, since a real failure happened while trying to read from the socket.
catch (SocketTimeoutException ignEx) {
// -- ignore exception, as we are expecting timeout exceptions because
// -- there might be nothing to read
}
catch (IOException ioEx) {
throw new SomeException (...);
}
As for declaring both in the method signature, It is not necessary to declare both in the throws clause, but it would be useful to the users of your method if you document both exceptions in the JavaDoc comments, and describe the conditions in which each of them are thrown.

Declare method to throw an exception and subclass of this exception

Is it meaningful to declare a method to throw an exception
and a subclass of this exception,
e.g. IOException and FileNotFoundException?
I guess that it is used in order to handle both exceptions by a caller method differently.
However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
Absolutely. You can still catch them separately:
try {
methodThrowingIOException();
} catch (FileNotFoundException e) {
doSomething();
} catch (IOException e) {
doSomethingElse();
}
So it makes no difference to what the caller can do if the method declares both - it's redundant. However, it can emphasize exceptions that you might want to consider. This could be done better in Javadoc than just the throws declaration.
Is it meaningful to declare a method to throw an exception and a subclass of this exception, e.g. IOException and FileNotFoundException?
Usually not - most IDEs I know of even issue warnings for such declarations. What you can and should do is to document the different exceptions thrown in Javadoc.
However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
Yes it is, you just need to ensure that the catch blocks are in the right order, i.e. more specific first. Catch blocks are evaluated in the order they are defined, so here
try {
...
} catch (FileNotFoundException e) {
...
} catch (IOException e) {
...
}
if the exception thrown is a FileNotFoundException, it will be caught by the first catch block, otherwise it will fall to the second and dealt with as a general IOException. The opposite order would not work as catch (IOException e) would catch all IOExceptions including FileNotFoundException. (In fact, the latter would result in a compilation error IIRC.)
However, is it possible to handle both exceptions if the method throws only the most generic i.e >IOException?
catch(IOException ex){
if(ex instanceof FileNotFoundException){}
}
But this doesn't look clean, Throwing both exception looks good, even caller would come to know to that this method may throw these these exceptions, so they will handle it properly
Yes, it's possible to handle both if the method only throws IOException.
The best way to answer such a question is to write a test to demonstrate it and try it out. Let the JVM tell you the answer. It'll be faster than asking here.
yes. when certain specialized exceptions can be handled correct. It is, if you handle the exceptions as follow:
try {
} catch (FileNotFoundException f) {
//Try a different file
} catch (IOException ioe) {
//Fatal, Maybe bad blocks ... Bail out...
} catch (Exception e) {
//Something went wrong, see what it is...
}
Declaring, that the method may throw (more generic) IOException, and (more specific) FileNotFoundException is usually a good thing - it's an additional information for people using your code later. Note that you should explicitely state in the JavaDoc, under what circumstances is each of the exceptions thrown.
They will still be able to distinguish the exceptions, and handle them differently using catch constructs like this one:
try {
yourAwesomeMethod()
} catch (FileNotFoundException ex) {
// handle file-not-found error
} catch (IOException ex) {
// handle other IO errors
}

How to fix SQLException in the Catch Statement?

This program is about auto complete. When I type something to the textfield, a list of suggestions will appear.
I make the method onWordUpdated() for a list of suggestions from the DB when I type something to the textfield.
Now, the problem is I have this error:
exception java.sql.SQLException is never thrown in body of corresponding try statement
I made a comment in the code so that you will know which line.
Could someone help me how to fix this?
thanks..
I have this code:
public void onWordUpdated(final String toComplete)
{
new Thread(new Runnable()
{
public void run()
{
try
{
final List<Suggestion> suggestions = suggestor.getSuggestions(toComplete);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
suggestionWidgetModel.clear();
for (Suggestion suggestion : suggestions)
suggestionWidgetModel.addElement(suggestion.getCaption());
if (!suggestions.isEmpty())
suggestionWidget.setSelectedIndex(0);
}
catch (SQLException e) // This line is my problem, Could someone help me how to fix this? Thanks..
{
e.printStackTrace();
}
}
});
}
catch (SQLException e1)
{
onSqlError(e1);
}
}
}, "onWordUpdated").start();
}
The compiler is simply telling you that you don't need to catch that exception at that point.
SQLException is a checked exception, which means that your code should only see it if you either explicitly throw it, or you call a method that declares it in its throws clause. Neither of these is true for the code in that particular try/catch block.
You should be able to just get rid of the inner try/catch block and probably the outer one too.
IIRC, it is theoretically possible to see checked exceptions that haven't been declared, but this unlikely to arise unless you take special steps to make it happen.
Java has two types of exceptions: unchecked (those that inherit from RuntimeException or Error) and checked (all others that inherit from Exception).
A checked exception has the following properties:
If a block of code throws one, it must be caught in a catch block or the method must declare that it may throw that type of Exception.
If some code calls a method that throws SomeException, that code must also be in a try-catch or its method must also specify throws SomeException.
Because of the first two checks, the compiler can detect whether a checked exception can actually be thrown in a certain block of code. As a result, this leads to a third property:
If the catch clause of a try-catch block declares an Exception type that cannot occur in the try block, then a compile error is generated. The compiler does this primarily to tell you that you've made an error: you're dealing with an exception that will never be thrown.
SQLException is a checked exception so it is subject to those rules. None of the lines of code (or the methods they call) in the try block below can ever throw a SQLException so the compiler tells you via a compile error.
try {
suggestionWidgetModel.clear();
for (Suggestion suggestion : suggestions)
suggestionWidgetModel.addElement(suggestion.getCaption());
if (!suggestions.isEmpty())
suggestionWidget.setSelectedIndex(0);
}
catch (SQLException e) // This line is my problem, Could someone help me how to fix this? Thanks..
{
e.printStackTrace();
}

Categories