How to fix SQLException in the Catch Statement? - java

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();
}

Related

Fatal exception handling in Java

I am creating a basic math parser with Java and doing this is revealing my shallow understanding of Java exception handling.
when I have this input:
String mathExpression = "(3+5";
and I subsequently call:
throw new MissingRightParenException();
the IDE forces me to surround with a try/catch like so:
try {
throw new MissingRightParenException();
} catch (MissingRightParenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
however, in order to force this to be a fatal exception, it looks like I have to add my own code to call System.exit(), like so:
try {
throw new MissingRightParenException();
} catch (MissingRightParenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
I am not sure I understand the syntax behind all of this, especially why I have to use a try/catch block around throwing an exception.
what is the rhyme and reason behind this?
Instead of throwing the exception, I could do this instead:
new MissingRightParenException();
instead of calling
throw new MissingRightParenException();
so I guess my question is - if this is a fatal exception, what is the best way to make it truly fatal while giving the user the best feedback?
If you want to have a checked exception that you have to catch - but not right away - then you can define throws MissingRightParenException in the signature of your methods.
class MissingRightParenException extends CalculationException {
...
}
class CalculationException extends Exception {
...
}
class MyClass {
int myMathRelatedMethod(String calculation) throws CalculationException {
...
if (somethingWrong) {
throw new MissingRightParenException("Missing right paren for left paren at location: " + location);
}
...
}
public static void main(String ... args) {
...
try {
myMathRelatedMethod(args[0]);
} catch (CalculationException e) {
// stack trace not needed maybe
System.err.println(e.getMessage());
}
...
}
}
You can also define it as the cause of a RuntimeException but that doesn't seem a good match for your current problem.
try {
...
throw new MissingRightParenException();
...
} catch (MissingRightParenException e) {
// IllegalStateException extends (IS_A) RuntimeException
throw new IllegalStateException("This should never happen", e);
}
If your MissingRightParenException class extends RuntimeException then you don't have to catch it. The message will fall through all methods where it (or it's parent classes such as Throwable, Exception and RuntimeException) is not explicitly caught. You should however not use RuntimeExceptions for input related errors.
Usually the user will get the stack trace or at least the error message, although that depends of course or the error handling further down the line. Note that even main does not have to handle exceptions. You can just specify throws Exception for the main method to let the console receive the stack traces.
So in the end: use throws in the signature of your methods instead of catching exceptions before you want to handle them.
Assuming that your exception is currently a subclass of Exception, which is a Checked Exception, you need to handle in a try catch. If you can make your exception a RunTimeException, you no longer need to do the try-catch stuffs.
what is the best way to make it truly fatal while giving the user the
best feedback?
Personally, I don't think a missing parenthesis should be a Fatal exception. The user should have the possibility to re-try.
However, if you really want to know, It is not possible with java to create a custom fatal exception as fatal exception means something went wrong on the system/jvm, not on the program itself. Still, you should change System.exit(0) to System.exit(1) or anything not equal to 0 as a program exiting with 0 as error code mean everything went right which is not the definition of an exception.
I am not sure I understand the syntax behind all of this
Basically what you do here is throw an exception so you have two choices, either catch it or re-throw it but anyway it will have to be caught somewhere. Then in the catch you simply end the program returning an error code meaning that something failed System.exit(1)
See this Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java for a better understanding of error code.
If MissingRightParenException is a checked exception (that seems to be the case, otherwise your IDE wouldn't be "nagging") then either you have to wrap it inside a try ... catch block or declare it via a throws clause in the method definition. The latter allows you to "bubble up" the exception and catch in the caller of your method throwing the MissingRightParenException exception.
Did you think about a throws clause?

Java : Unknown error in exception handling

i have a weird question. i had a quiz in my class today. One portion of the quiz was to find and correct errors in a short piece of code. one of the questions was like this
class Example {
public static void main(String[] args) {
try {
System.out.println("xyz");
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("abc");
}
}
}
I thought there was no error in the program but my professor insisted that there was. Can anyone guess what the error is?
The "error" may be that you don't need to handle any exception here: System.out.println does not specify any checked exception. It could simply be:
public static void main(String[] args) {
System.out.println("xyz");
}
Since the Exception class covers both checked and unchecked exceptions, then if you add a catch block here, in this case you would be handling only unchecked exceptions, which you should not normally handle.
There is no Error in the Above Program , but also there is no need to put a try{} catch{} ....since you don't use any code that can throw an Exception , for example a risky method like Thread.sleep();
So maybe that’s what your professor meant .
Well, I see nothing that would keep this from compiling, but I do see some problems. To begin with, there are comments indicating the presence of code which is not there. Comments out of sync with code is always a problem.
[EDIT: indentation errors have been edited away] And you're catching Exception e, which you really oughtn't to do. You should always catch a specific exception that you expect to encounter, and handle it specifically. Since there's no exception that System.out.println can throw, this would make the whole Exception handling block a problem.
The following code snippet would throw a compilation error if used with IOException, since System.out.println would never throw an IOException but could throw Exception or Throwable which is its super class.
try {
System.out.println("xyz");
} catch (IOException e) {
//simple display error statement here
} finally {
//simple print statement here
}

Which Exception class to use?

I have written a music player in Java, but I have a problem with finding an exception to throw. Basically, what I want the exception handler to throw is if a filename of a song stored in the playlist is altered or if the file is deleted, as naturally, in that case it won't play. I first thought it was an IOException I would need, but it gave me the error saying
exception IOException is never thrown in body of corresponding try statement
Now, I understand that that means that I'm working with the wrong Exception class, and so I tried to write my own that extends Exception, but it gives me the same error when I try to compile. Can anyone see what I'm doing wrong?
This is the method as it is right now:
public void play() throws NoMatchException
{
if(player != null) {
player.stop();
}
try{
int fileToPlay = tracklist.getSelectedIndex();
String filename = organizer.getFile(fileToPlay);
Media song = new Media(filename);
player = new MediaPlayer(song);
setVolume(currentVolume);
player.play();
player.setOnEndOfMedia(new Runnable() {
#Override public void run() { next(); }
});
}
catch (NoMatchException e){
//Some exception
}
}
When you are not sure what exception you need to catch, go to the documentation of the corresponding method. It turns out that the constructor of Media would throw MediaException - this is the exception that you need to catch. Scroll down to the "throws" section, and look for the exceptions that do not extend RuntimeException (runtime exceptions usually indicate programming errors; the need to catch this is rare).
When you are deciding to catch an exception at a particular level of your program, see if your code can do something meaningful about it. You shouldn't be catching exceptions unless you know what to do when to catch them.
This code makes no sense.
Your catch block is empty and does nothing. Your method says it throws a NoMatchException. Why don't you eliminate the try/catch and let it do so?
You catch exceptions when you have a viable strategy for recovering. Doing nothing is not a strategy. Just let it bubble up and let the caller deal with it.
If you do have a viable recovery strategy, implement it in the catch block and remove the throws clause from the method signature. Either one or the other, but not both.

Is it possible to ignore an exception?

In Java, is it possible to make a method that has a throws statement to be not checked.
For example:
public class TestClass {
public static void throwAnException() throws Exception {
throw new Exception();
}
public static void makeNullPointer() {
Object o = null;
o.equals(0);//NullPointerException
}
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm forced to handle the exception, but I don't want to
}
}
You can try and do nothing about it:
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) { /* do nothing */ }
}
Bear in mind, in real life this is extemely ill-advised. That can hide an error and keep you searching for dogs a whole week while the problem was really a cat(ch). (Come on, put at least a System.err.println() there - Logging is the best practice here, as suggested by #BaileyS.)
Unchecked exceptions in Java extend the RuntimeException class. Throwing them will not demand a catch from their clients:
// notice there's no "throws RuntimeException" at the signature of this method
public static void someMethodThatThrowsRuntimeException() /* no need for throws here */ {
throw new RuntimeException();
}
Classes that extend RuntimeException won't require a throws declaration as well.
And a word from Oracle about it:
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
There are 3 things you can do :
Throw a RuntimeException (or something extending a RuntimeException, like NullPointerException, IllegalArgumentException,...), you don't have to catch these as they are unchecked exceptions.
Catch the exception and do nothing (not recommended) :
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) {
// Do nothing
}
}
Change exceptionTest () declaration to say that it throws an Exception, and let the method calling it catch the Exception and do what is appropriate :
public static void exceptionTest() throws Exception {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm no more forced to handle the exception
}
In Java there is two kinds of Exceptions, Checked Exceptions and Unchecked Exceptions.
Exception is a checked exception, must caught or thrown.
NullPointerException is a RuntimeException, (the compiler doesn’t forces them to be declared in the throws claus) you can ignore it, ,but it still may occur in the Runtime, and your application will crash.
From Exception documentation:
The class Exception and any subclasses that are not also subclasses of
RuntimeException are checked exceptions. Checked exceptions need to be
declared in a method or constructor's throws clause if they can be
thrown by the execution of the method or constructor and propagate
outside the method or constructor boundary.
From the RuntimeException documentation:
RuntimeException is the superclass of those exceptions that can be
thrown during the normal operation of the Java Virtual Machine.
RuntimeException and its subclasses are unchecked exceptions.
Unchecked exceptions do not need to be declared in a method or
constructor's throws clause if they can be thrown by the execution of
the method or constructor and propagate outside the method or
constructor boundary.
No, it raises a compiler error. Being a checked exception, you must either catch it or propagate it by declaring your method as potentially throwing it.
Check this and this.
Throw a RuntimeException or an exception which is derived from RuntimeException. Then the compiler will not force you to catch it.
The other answers are right, in that they correctly tell you what you should do, but it is actually possible to throw a undeclared checked exception. There are a few ways this can be done; the simplest is:
public void methodThatSecretlyThrowsAnException() {
Thread.currentThread().stop(new Exception());
}
or if your goal is to wrap an existing method that does declare its exception
public void methodThatSecretlyThrowsAnException() {
try {
methodThatAdmitsItThrowsAnException();
} catch(final Exception e) {
Thread.currentThread().stop(e);
}
}
(Needless to say, you should never do this.)
Just catch an exception and dont do any thing with it, leave it as it is and catch the generic exception in case you are not aware of the specific exception
try{
//Your logic goes here
}
catch(Exception e)//Exception is generic
{
//do nothing
}
AS I know, it's impossible in the case. Only unchecked exception, compiler can skip to check. such as RuntimeException.
You can use a loophole in the Java Compiler. Add the following code:
public RuntimeException hideThrow(Throwable e) {
if (e == null)
throw new NullPointerException("e");
this.<RuntimeException>hideThrow0(e);
return null;
}
#SuppressWarnings("unchecked")
private <GenericThrowable extends Throwable> void hideThrow0(Throwable e) throws GenericThrowable {
throw (GenericThrowable) e;
}
You can catch the exception, then invoke hideThrow with the exception to throw it without the compiler noticing. This works because of type erasure. At compile time, GenericThrowable represents RuntimeException because that is what we are passing. At run time, GenericThrowable represents Throwable because that is the basic type in the type parameter specification.
It is not advisable to avoid an exception with an empty catch block even though you are completely sure that is not going to fail under any circumstance. Sometimes, we are not aware of the human factor.
If you are sure that an exception is very unlikely to happen (if not impossible) you should create your own Exception and and wrap the unexpected exception in it.
For example:
private class UnlikelyException extends RuntimeException {
public UnlikelyException (Exception e){
super (e);
}
}
Then wrap your code with a try-catch block and throw your exception, which you don't have to catch
try {
// Your code
} catch (Exception e) {
throw new UnlikelyException(e);
}

Change unhandled exception auto-generated catch code in Eclipse?

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
}

Categories